LoginSignup
0
1

More than 3 years have passed since last update.

[WPF]子要素のBindingを忘れて親要素が勝手にBindingされる問題

Posted at

問題

ビジュアルツリー上の親子関係があり親子で同名のプロパティをBindingしていた時、子要素のBindingがされていないと親要素のプロパティがBindingされて表示されてしまいました。

具体的にコードで示してみます。
まず、親要素MainWindowに子要素SubWindowを表示します。

MainWindow.xaml
<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しておきます。

SubWindow.xaml
<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を紐づけます。

MainWindow.xaml.cs
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }

MainViewModelではプロパティMessageに値を入れておきます。

MainViewModel.cs
    internal class MainViewModel
    {
        public string Message { get; } = "MainWindow";
    }

■実行結果
image.png

原因

SubWindowのMessageでは、親要素MainWindowのMessageがBindingされて「MainWindow」が表示されていることが分かります。
これは、SubWindowでDataCotextがBindingされていないため、親要素MainWindowのDataContextがBindingされてしまったためです。

因みに

DataContextが継承される件は、WPF、怒りのツリー外DataContext伝播によると、WEPerには常識のようです・・・。悲しい。

PrismのRegionManagerで画面遷移していたりすると気づきにくく発見が遅れました。改めて基礎大事。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1