トップ回答者
INotifyPropertyChangedを実装しても変更が通知されません

質問
-
INotifyPropertyChangedを実装しても変更が通知されません。どのようにすれば変更が通知されるのでしょうか?
■目的
MVVMのViewModelを実装したい。
■期待する動作
TextBoxに名前を入力して、フォーカスを移動するとTextBlockに反映される。
■実際の動作
TextBoxに名前を入力してもTextBlockに反映されない。Nameクラスのセッターにブレークポイントを設定して、TextBoxに入力したがプロパティのセッターが呼ばれていない。
■試したこと- TextBlockのBindingに「Mode=OneWay」を追記
- TextBoxのBindingに「Mode=TwoWay」を追記
動作は変わりませんでした。■ソース
MainWindow.xaml
<Window x:Class="HelloWorld.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation " xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml " Title="MainWindow" Height="150" Width="200"> <StackPanel> <TextBlock Text="{Binding Path=Name.Last}" /> <TextBlock Text="{Binding Path=Name.First}" /> <TextBox Text="{Binding Path=Name.Last}" /> <TextBox Text="{Binding Path=Name.First}" /> </StackPanel> </Window>
Name.cs
using System.ComponentModel; namespace HelloWorld { public class Name : INotifyPropertyChanged { private string first; public string First { get { return first; } set { first = value; OnPropertyChanged("First"); } } private string last; public string Last { get { return last; } set { last = value; OnPropertyChanged("Last"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
■環境
Visual Studio 2010 SP1, .NET Framework4
Blog:プログラマーな日々 http://d.hatena.ne.jp/JHashimoto/
- 編集済み J.Hashimoto 2011年3月24日 23:44 環境を追記
回答
-
Binding 構文でバインディングソースを指定していないってことは、その要素の DataContext をバインディングソースとすることになりますが、どこかで設定されていますか?
さらに、その Path の指定だと「バインディングソースに設定しているオブジェクトの Name プロパティが指すオブジェクトの、First/Last プロパティ」という意味になりますが大丈夫ですか?
- 回答としてマーク J.Hashimoto 2011年3月25日 0:15
すべての返信
-
Binding 構文でバインディングソースを指定していないってことは、その要素の DataContext をバインディングソースとすることになりますが、どこかで設定されていますか?
さらに、その Path の指定だと「バインディングソースに設定しているオブジェクトの Name プロパティが指すオブジェクトの、First/Last プロパティ」という意味になりますが大丈夫ですか?
- 回答としてマーク J.Hashimoto 2011年3月25日 0:15
-
解決出来ました。Hongliangさんありがとうございました。
Binding 構文でバインディングソースを指定していないってことは、その要素の DataContext をバインディングソースとすることになりますが、どこかで設定されていますか?
設定していませんでした。
新たにMainWindow.csを追加して、そこで設定するようにしました。
using System.Windows; namespace HelloWorld { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new Name(); } } }
さらに、その Path の指定だと「バインディングソースに設定しているオブジェクトの Name プロパティが指すオブジェクトの、First/Last プロパティ」という意味になりますが大丈夫ですか?
Pathの指定も修正しました。
<Window x:Class="HelloWorld.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="150" Width="200"> <StackPanel> <TextBlock Text="{Binding Path=Last}" /> <TextBlock Text="{Binding Path=First}" /> <TextBox x:Name="txtLast" Text="{Binding Path=Last}" /> <TextBox x:Name="txtFirst" Text="{Binding Path=First}" /> </StackPanel> </Window>
Blog:プログラマーな日々 http://d.hatena.ne.jp/JHashimoto/