I have this simple application that adds some items to a combobox:
public partial class Window1 : Window
{
private ObservableCollection<string> _dropDownValues = new ObservableCollection<string>();
public ObservableCollection<string> DropDownValues
{
get { return _dropDownValues; }
set { _dropDownValues = value; }
}
private string _selectedValue;
public string SelectedValue
{
get { return _selectedValue; }
set { _selectedValue = value; }
}
public Window1()
{
InitializeComponent();
DataContext = this;
DropDownValues.Add("item1");
DropDownValues.Add("item1");
DropDownValues.Add("item1");
DropDownValues.Add("item1");
DropDownValues.Add("item1");
DropDownValues.Add("item1");
}
}
And here is the XAML file:
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel HorizontalAlignment="Left" Margin="10">
<ComboBox
Margin="0 0 0 5"
ItemsSource="{Binding DropDownValues}"
SelectedValue="{Binding SelectedValue}"
Width="150"/>
</StackPanel>
</Window>
Can someone show me how can I set the DataContext from the xaml file instead of initializing in the constructor ?
Thanks.
The DataContext property is the default source of your bindings, unless you specifically declare another source, like we did in the previous chapter with the ElementName property. It's defined on the FrameworkElement class, which most UI controls, including the WPF Window, inherits from.
DataContext is inherited to all lower Elements of the XAML and to all the XAML of UserControl s unless it is overwritten somewhere. By setting the UserControl DataContext to itself, this overwrites the DataContext and breaks Inheritance. Instead, nest it one Element deep in the XAML, in your case, the StackPanel .
The DataContext is the source of all entities mapped over a database connection. It tracks changes that you made to all retrieved entities and maintains an "identity cache" that guarantees that entities retrieved more than one time are represented by using the same object instance.
Just change the Window
to bind DataContext
to itself:
<Window x:Class="WpfApplication2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}" ... />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With