Set DataContext to XAML

I have this simple application that adds some elements to a combo box:

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.

+6
source share
2 answers

Just change Window to the DataContext binding 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}}" ... /> 
+23
source

I believe that the DataContext in this scenario is implicit and does not need to be set as you are using the code behind. If you used MVVM, you would add a link to this folder and class inside your XAML markup and set the resource key to a value that can then be declared as a DataContext inside a child of the DataContext. But in your case (since you are not using MVVM), you do not need to do this.

0
source

Source: https://habr.com/ru/post/895885/


All Articles