Databinding the Right way for Image Sources

Greetings /r/csharp,

Currently I'm developing a small weather app that extracts the weather from a JSON api. The weather is then rendered on screen.

The API is split into a couple of different data types, a list and some strings. The condition is what I'm focusing on, Previously I have been able to bind the values of the conditions using the following syntax.

 <Image HorizontalAlignment="Left" Height="107" Margin="181,26,0,0" VerticalAlignment="Top" Width="136"> <Image.Style> <Style TargetType="{x:Type Image}"> <Style.Triggers> <DataTrigger Binding="{Binding Condition}" Value="Partly Cloudy"> <Setter Property="Source" Value="http://packapplication:,,,/Images/cloud.png"></Setter> </DataTrigger> <DataTrigger Binding="{Binding Condition}" Value="Fair"> <Setter Property="Source" Value="http://packapplication:,,,/Images/rain.png"></Setter> </Style.Triggers> </Style> </Image.Style> </Image> 

So when the app is running if the Condition string is set to Mostly Cloudy, the image is then meant to render. I have also attempted a manual version of this bind to make sure everything is in place however I'm aware this isn't the MVVM method and is considered hacky.

Inside the mainwindow.xaml.cs (this version works but isn't really the MVVM way)…

 switch (Forty) { case "Partly Cloudy": img.Source = new BitmapImage(new Uri("images/cloud.png", UriKind.Relative)); break; case "Fair": img.Source = new BitmapImage(new Uri("images/rain.png", UriKind.Relative)); break; } 

So when the Get() Process is run, the routine checks the string also being grabbed for use. it then renders the image in place.

So my question is this, How can I approach binding the data using the MVVM approach? I have researched INotifyProperty however it requires boolean values rather than strings. I'm a tad confused, If anyone could provide an example approach as to how they would do this without the hacky parts and explain there approach to INotifyPropertyChanged. I would be greatful. My full source code is available on github, The class.

by Oli_Picard via /r/csharp

Leave a Reply