[英]How to acces Model properties in WPF using MVVM Light
我是MVVM和WPF的新手,所以這可能是一個廣泛或愚蠢的問題,但是:
我正在使用MVVM模式,並且具有1個Viewmodel,多個視圖和幾個模型。 所有的視圖只是放在我的mainwindow.xaml中的Usercontrols。
有問題的視圖綁定到具有多個屬性的模型,我想使用其中一個屬性動態更改用戶控件中的圖片。
我在嘗試訪問此屬性時遇到了非常困難的時間,我的問題是如何以“正確的” MVVM方式執行此操作。
我的mainwindow.xaml:
<Window.Resources>
<DataTemplate DataType="{x:Type Model:Device}">
<Canvas>
<View:DeviceUserControl/>
</Canvas>
</DataTemplate>
</Window.Resources>
//---- SNIP----
<Grid Name="grid1">
<ItemsControl ItemsSource="{Binding Devices}" />
</Grid>
DeviceUserControl.xaml
//--- SNIP ---
Image Name="DeviceImage" Source="{StaticResource IconAdd}"/>
設備型號
//--- SNIP ---
public enum Typeenum
{
FrequenceGenerator,
Oscilloscope,
Test1,
Test2
};
public Typeenum Type { get { return type; } set { type = value; NotifyPropertyChanged("Type"); } }
我想根據對象的類型更改DeviceImage 。 我嘗試了dependencyproperties,但是它沒有按預期工作(每次都返回相同的類型)。 我真的不需要notifyPropertyChanged,因為我只在實例化Usercontrol時才對更改圖像源感興趣。
首先,應將視圖綁定到ViewModels,而不是Models。 至少這就是MVVM的全部意義所在。 另外,如果您希望在屬性更改時發生某些事情,那么一種方法是在ViewModel中訂閱PropertyChanged
事件(我假設您知道應該實現INotifyPropertyChanged
接口),然后將邏輯放在屬性更改上那里。
代碼樣例
this.PropertyChanged += (s,e)=>{
// Your code here.
// e.g. this.MyImageSource = "http://img.com/image.jpg"
}
該代碼示例假定屬性更改事件稱為PropertyChanged
,並且圖像控件的源是綁定到ViewModel中MyImageSource
屬性的數據。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.