简体   繁体   中英

How to acces Model properties in WPF using MVVM Light

I am new to MVVM and WPF so this might be a broad or a dumb question, but:

I am using the MVVM pattern and have 1 Viewmodel, several views and a couple of models. All of the views are just Usercontrols which are put on my mainwindow.xaml.

The view in question is bound to a model wich have several properties, one of which i want to use to dynamically change a picture in the usercontrol.

I am having a very difficult time trying to acces this property and my question is how i do this the "right" MVVM way.

My 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}"/>

DeviceModel

//--- SNIP ---
public enum Typeenum
{
 FrequenceGenerator,
 Oscilloscope,
 Test1,
 Test2
};
public Typeenum Type { get { return type; } set { type = value; NotifyPropertyChanged("Type"); } }

I want to change the DeviceImage based on the type of the object. I have tried dependencyproperties, but it didnt work as expected (It returned the same type everytime). I dont really need the notifyPropertyChanged as i am only interested in changing the image source when the Usercontrol is instantiated.

First of all, you should bind Views to ViewModels, not Models. At least that's what MVVM is all about. Also, if you want something to happen when a property changes, then one way is to subscribe to the PropertyChanged event in your ViewModel (which I assume you know should implement the INotifyPropertyChanged interface) then put your logic on what should happen on the property change there.

Code Sample

this.PropertyChanged += (s,e)=>{
    // Your code here.
    // e.g. this.MyImageSource = "http://img.com/image.jpg"
}

The code sample assumes that your event for the property changes is called PropertyChanged and that the image control's source is data bound to the MyImageSource property in the ViewModel. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM