我有綁定到一個ViewModelViewModel中的MVVM屬性?
DataContext="{Binding MyViewModel, Source={StaticResource Locator}}">
文本框,...被綁定到propertys IN的視圖模型視圖:
<TextBox Text="{Binding MyValue, Mode=TwoWay}"/>
<TextBlock Text="{Binding DisplayValue}"/>
屬性,視圖模型:
public MyViewModel()
{
DisplayValue = "0€";
MyValue = "0";
}
private string _myvalue;
public string MyValue
{
get
{
return _myvalue;
}
set
{
_myvalue = value;
ChangeValue();
RaisePropertyChanged(() => MyValue);
}
}
private string _displayvalue;
public string DisplayValue
{
get
{
return _displayvalue;
}
set
{
_displayvalue = value;
RaisePropertyChanged(() => DisplayValue);
}
}
private void ChangeValue()
{
//do something here and change the values of the property, e.g.:
DisplayValue = MyValue + "€";
}
這只是一個剪輯。我通常在VIEWMODEL裏有50個屬性,所有的方法也都在ViewModel中(意思是RelayCommands和方法,這些方法將在約50%屬性的setter中被調用)。如您所見,我沒有使用任何模型。這是使用MVVM的正常方式,還是應該創建一個新類並將所有屬性/方法放入新類(Model)中?但是,我該如何將視圖中的元素與Model,當視圖DataContext綁定到ViewModel時?
編輯:說清楚。 我有一個文本框,文本框綁定到ViewModel中的一個屬性。這是使用MVVM的正確方法嗎?我是否應該僅在有List(例如ComboBox)時使用模型類,或者當我有幾個TextBox(這會在我的眼睛中有點愚蠢和不必要)?
好吧,這可能是一個愚蠢的評論,但你有沒有測試過這段代碼? 從我可以讀,當你設置myvalue的,你提高PropertyChanged事件,然後調用給ChangeValue()方法,該方法將設置myvalue的屬性,這將提高PropertyChanged事件,這將調用ChangeValue()方法,將設置MyValue屬性...等等。 除非MyValue + =「€」不使用Setter,但我嚴重懷疑這一點。 似乎是一個很好的舊的無限循環/記憶leack。但同樣,我沒有測試它自己,所以我可能是錯的;) – Miiite
是的,你是對的...愚蠢的例子,要去改變(編輯) – Rudi