views:

270

answers:

2

I've got some code which sets up a datacontext. Often enough, the datacontext should be set to some underlying data collection, such as an ObservableCollection - but occasionally I'd like to set it to a collection that is itself a dependency property.

This can be done in xaml, but doing so defeats the purpose, which is to share the UI code between both scenarios.

Let's say I have a dependency property:

public static readonly DependencyProperty MyDataProperty = [whatever];

and elsewhere, I have a control that expects me to setup the datacontext:

myGreatControl.DataContext = ???

How can I set the above datacontext to refer to the collection stored in the dependency property?

The following question seems related: http://stackoverflow.com/questions/1126490/silverlight-programmatically-binding-control-properties

But I'd like not to bind one property to another, but a property to a datacontext. The advantage of that is that I don't need to know the type or name or even purpose at the binding code - any FrameworkElement has a datacontext, and I have an (updateable) property I'd like to bind to it.

A: 

normally, when you set a binding if you don't explicitly set the object that it is bound to, only the path to the member, it uses the DataContext object.

for example....

<TextBlock Text="{Binding MyProperty}"/>

binds the text to the property "MyProperty" of the DataContext--not a specific collection. You can see this in ControlTemplates, like for ListBox items. As long as your DataContext has the "MyProperty" property you will be fine.

You can also bind directly to the DataContext like this...

<TextBlock Text="{Binding}"/>

I tend to do this with the parent container...

<Grid DataContext="{Binding}">
    <TextBlock Text="{Binding MyProperty}"/>
</Grid>
Muad'Dib
I'm not exactly sure what you're getting at - if I did this, I'd need to modify the xaml for each case. I'm trying to generically use a particular control, and programmatically "connect it up" to whatever the source happens to be - so, the control doesn't know compile-time whether I'm actually binding to `MyProperty` or some code-behind collection.That's why I want to be able to bind to a collection directly or some other property.
Eamon Nerbonne
A: 

The lovely thing about spending time figuring out how to ask your question is that sometimes you realize it's blindingly obvious...

I said I'd like not to bind one property to another, but a property to a datacontext - well, turns out, FrameworkElement.DataContext is just a dependency property; specifically, FrameworkElement.DataContextProperty.

In short, I can just do:

Binding binding = new Binding("MyData") {
    Mode = BindingMode.OneWay,
    Source = this,
};
myGreatControl.SetBinding(FrameworkElement.DataContextProperty, binding);

Sorry 'bout the question - hopefully this question will save an equally flummoxed coder some time.

Eamon Nerbonne