我有一個真正簡單的例子,我有一個項目 類實現INotifyPropertyChanged是很好的工作沒有一個視圖模型:Silverlight的MVVM視圖模型查看約束力不工作
public class Item : INotifyPropertyChanged
{
private string _name;
private string _desc;
public string Name
{
get
{ return _name; }
set
{
if (_name == value)
return;
_name = value;
this.OnPropertyChanged(new PropertyChangedEventArgs("Name"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public Item()
{
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, e);
}
}
該作品在一個簡單的例子,我有下面的代碼背後:
public MainPage()
{
InitializeComponent();
item = new Item() { Name = "john", Description = "this is my name" };
LayoutRoot.DataContext = item;
}
,如果我有一個按鈕,在代碼中調用命令處理程序背後我看到改變 到簡單的用戶界面爲的PropertyChanged由於 的Twoway綁定在我的文本屬性上,因此「事件正在」收聽「。處理程序是這樣的:
private void Button_Click(object sender, RoutedEventArgs e)
{
item.Name = "ted";
item.Description = "adddress";
}
所以當然這改變了用戶界面(我說這是真正簡單的例子) 現在我介紹一個視圖模型,並更改到簡單的模型沒有反映 沒有一個傾聽財產變化。
我設置的視圖中的視圖模型DataContext的,事實上這是代碼視圖中唯一的一行:
LayoutRoot.DataContext = new MyViewModel();
現在我的視圖模型的樣子:
public class MyViewModel
{
Item item = null;
public ICommand ChangeCommand { get; private set; }
public MyViewModel()
{
item = new Item() { Name = "john", Description = "jjjj" };
ChangeCommand = new DelegateCommand<string>(OnChange);
}
private void OnChange(string title)
{
item.Name = "bill";
}
注: 我使用的模式和實踐命令從XAML發射事件到Viewmodel 和這個偉大工程
我的處理程序再次改變了item.name,導致setter被調用,並且 this.OnPropertyChanged(new PropertyChangedEventArgs(「Name」));被叫,但沒有人是 傾聽,所以沒有改變。
我想保持這個例子真正簡單,有些人會說太簡單,但我只想 知道爲什麼綁定不起作用。我可以從視圖拉ViewModel,但我需要 能夠做到相反。我想知道我錯過了什麼。
我想我正確地猜出了你的問題,但問題會更清楚,如果你另外包含XAML數據綁定代碼。 – 2009-10-19 01:19:54