I have a simple dialog box that inherits from Window, and I set its DataContext in XAML as follows:
<Window x:Class="MyProject.MyDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
...>
<StackPanel>
<TextBox Text="{Binding SomeText}"/>
...
</StackPanel>
</Window>
and here, as I show this dialog box:
var dialog = new MyWindow();
MyWindow.SomeText = "some text";
if (dialog.ShowDialog() == true)
...
For some reason, this does not set the source text of the text field to "some text" when creating the window and there are no binding errors.
However, if I set the data context for the StackPanel instead of the window:
<StackPanel DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}">
...
</StackPanel>
everything works as expected.
What is the difference between the two? Why doesn't the first approach work?
source
share