問題
ビジュアルツリー上の親子関係があり親子で同名のプロパティをBindingしていた時、子要素のBindingがされていないと親要素のプロパティがBindingされて表示されてしまいました。
具体的にコードで示してみます。
まず、親要素MainWindowに子要素SubWindowを表示します。
<Window x:Class="WpfSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DoubleLoadWpf"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Orientation="Vertical">
<TextBlock Grid.Row="0" Text="MainWindow" Foreground="Red"/>
<TextBlock Grid.Row="0" Text="{Binding Message}" Foreground="Red"/>
</StackPanel>
<local:SubWindow Grid.Row="1"/>
</Grid>
</Window>
子要素SubWindowには、親要素のMainWindowと同名のプロパティMessageをBindingしておきます。
<UserControl x:Class="WpfSample.SubWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid>
<StackPanel Orientation="Vertical">
<TextBlock Grid.Row="0" Text="SubWindow" Foreground="Blue"/>
<TextBlock Grid.Row="0" Text="{Binding Message}" Foreground="Blue"/>
</StackPanel>
</Grid>
</UserControl>
親要素MainWindowのみBindingします。
コードビハインドでDataCotextとMainViewModelを紐づけます。
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
MainViewModelではプロパティMessageに値を入れておきます。
internal class MainViewModel
{
public string Message { get; } = "MainWindow";
}
原因
SubWindowのMessageでは、親要素MainWindowのMessageがBindingされて「MainWindow」が表示されていることが分かります。
これは、SubWindowでDataCotextがBindingされていないため、親要素MainWindowのDataContextがBindingされてしまったためです。
因みに
DataContextが継承される件は、WPF、怒りのツリー外DataContext伝播によると、WEPerには常識のようです・・・。悲しい。
PrismのRegionManagerで画面遷移していたりすると気づきにくく発見が遅れました。改めて基礎大事。