开发者

WPF/Silverlight: data binding a datacontext to a property programmatically

I've got some code which sets up a datacontext. Often enough, the datacontext sho开发者_开发问答uld 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: 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.


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜