Reputation: 51094
I have a small test window, like this:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="Combo" DisplayMemberPath="Word" ItemsSource="{Binding Numbers}" HorizontalAlignment="Left" Margin="115,27,0,0" VerticalAlignment="Top" Width="120" />
</Grid>
</Window>
With code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Numbers = new ObservableCollection<NumberWord>
{
new NumberWord {Number = 1, Word = "One"},
new NumberWord {Number = 2, Word = "Two"},
new NumberWord {Number = 3, Word = "Three"}
};
Combo.ItemsSource = Numbers;
}
public ObservableCollection<NumberWord> Numbers { get; set; }
}
I keep seeing answers to my other binding questions that state the explicit setting of Combo.ItemsSource = Numbers;
is unnecessary because I have the binding ItemsSource="{Binding Numbers}"
. I have also been told multiple times that I need not set a DataContext
on Combo
because the whole window is the data context, and Combo
inherits this data context.
My question is, why do I always - not just this combo - set ItemsSource
or other binding properties explicitly in code behind. Why is the XAML data binding not working?
Upvotes: 1
Views: 2208
Reputation: 410
you need to implement INotifyPropertyChanged. then use:
this.DataContext = this;
Upvotes: 0
Reputation: 18578
DataContext
is one of the DependancyProperties
which the child control inherits from the Parent if the local value is not set.
Hence if you set the DataContext
of Window
to something, the child controls including your ComboBox
will have it.
Now, in your case, you have not set the DataContext
of your Window
hence your Binding
of ItemsSource
is not working
If in the constructor of your window, after initializeComponent you do
DataContext = this;
then you need not to set the ItemsSource
of Combobox
in code behind
and your binding of ItemsSource
will work on your Combo.
Upvotes: 1
Reputation: 128136
The binding ItemsSource="{Binding Numbers}"
needs a source object, namely one that has a public Numbers
property. In your case this is the MainWindow instance.
So either you set the source explicitly by something like this:
ItemsSource="{Binding Numbers,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}"
or you set the source object by setting a DataContext
, e.g. in code behind:
public MainWindow()
{
InitializeComponent();
DataContext = this;
...
}
In case you need to change the value of the Numbers
property later, you also have to add a property change notification mechanism, like implementing the INotifyPropertyChanged
interface.
This is all well explained in the Data Binding Overview article on MSDN.
Upvotes: 2