ItemsControl with multiple DataTemplates for a viewmodel

You can create multiple ObservableCollections and then bind your ItemsSource to a CompositeCollection which joins those collections. Then in your XAML you can create different DataTemplates for the respective types using the DataType property which like styles gets automatically applied if it is placed in the resources. (You can also create the composite in XAML … Read more

WPF Canvas, how to add children dynamically with MVVM code behind

ItemsControl is your friend: <Grid> <Image Source=”…”/> <ItemsControl ItemsSource=”{Binding Points}”> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Canvas/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemContainerStyle> <Style> <Setter Property=”Canvas.Left” Value=”{Binding X}”/> <Setter Property=”Canvas.Top” Value=”{Binding Y}”/> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <Border BorderBrush=”Red” BorderThickness=”1″ Width=”{Binding Width}” Height=”{Binding Height}”/> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </Grid> The above assumes your VM exposes a collection of points via a Points property, and … Read more

ReSharper warnings with MVVM

You can use External Annotations to indicate to ReSharper the method is used and thus not to warn you. See the ReSharper docs on that here. You need to decorate any such methods with [UsedImplicitlyAttribute]. Before using the attribute, you see: and then, after applying the attribute: [UsedImplicitly(ImplicitUseTargetFlags.WithMembers)] class NotUsed { public int Field1 { … Read more

WPF binding not updating the view

You need to implement INotifyPropertyChanged in your ViewModel order to notify the View that the property has changed. Here’s a link to the MSDN page for it: System.ComponentModel.INotifyPropertyChanged The most important thing to note is that you should raise the PropertyChanged event in your property setter.

tech