I was working with some really fancy WPF code and using a style element. After finishing it i looked for my Resharper sidebar to figure out if it had some warnings  or suggestions in it. The properties I was binding to weren’t found in the datacontext so Resharper was giving me a hard time about this. So i figured i write a post about the different way to to this. I give examples about Style elements, UserControls, Windows and DataTemplates

Usercontrols/Windows etc.

<Window x:Class="WpfApp1.MainWindow"
        .......
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        .....
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800" d:DataContext="{d:DesignInstance local:MyViewModel}">
</Window>

Style elements

<Style>
    <d:Style.DataContext>
        <x:Type Type="local:MyType" />
    </d:Style.DataContext>
    <!--usual setters, triggers, etc.-->
</Style>

DataTemplates

<DataTemplate DataType="{x:Type local:User}">
    <StackPanel>
        <TextBlock Text="{Binding FirstName}" />
        <TextBlock Text="{Binding LastName}" />
    </StackPanel>
</DataTemplate>

The reason I wrote this post is that all these different ways are described somewhere on StackOverflow however they are all in different questions and not together on the same page.

Leave a Reply

Your email address will not be published. Required fields are marked *