I am a newbie in this Silverlight Databinding subject. I am starting to understand how cool is this declaratively way of data binding. To try it out, I have this listbox in my Page.xaml:
<ListBox Height="100" Name="lbCategories" Width="236" HorizontalAlignment="Left" Margin="20,0,0,0" SelectionMode="Multiple" ItemsSource="{Binding Categories}" DisplayMemberPath="Name" />
In my Page.xaml.cs I have a public property called Categories of the type ObservableCollection.
It works if this following line is present in my CS file:
DataContext = this;
But开发者_Go百科 I want to avoid any programatically databinding. I would like to set the DataContext to "this" in my ListBox element declarativelly. Is there any way of doing that?
Thanks, Oscar
The fact that the programmatic code you are trying to replace is:
DataContext = this;
means that you are trying to set the DataContext of the ListBox to a UI element, which is not how how DataContext is normally used. If you have properties exposed by a UI element, you don't need to use DataContext at all, just bind directly to the element. So instead of:
ItemsSource="{Binding Categories}"
use:
ItemsSource="{Binding Categories, ElementName=mainWindow}"
where mainWindow is the name of the element referred to by "this" above, and leave DataContext unset.
If for some reason you did want to use DataContext that way, you would use this attribute on the ListBox:
DataContext="{Binding ElementName=mainWindow}"
to set the DataContext to the element corresponding to your code-behind file.
Bind it to a static resource you define in the XAML as in this example.
精彩评论