WPF – the more you use the more you learn

WPF has abilities that maps extremely well into our declarative way of thinking. The more I use WPF the more I like it.

Today I had a requirement that the cells of a DataGrid in my UI should have a certain style depending on its value. This is of course not an uncommon requirement and I have implemented the very same requirement on numerous occasions before. But it turns out I have been doing it wrong!

Before I usually thought that this could not be done with the current generated UI from MDriven. Since the StyleRef expression available per column of the datagrid would not have the context of the row – but rather the context of the ViewModel.

But then I googled a bit and found the WPF DataTrigger. The DataTrigger can be used in a fixed style to take on different values based on data. Just the way I want!


In the model I can use a fixed style: “CoverWeeksStyle” and then in the WPF stylesheet I define the style like this:

  <wecpof:IntSmallerThan x:Key="IntSmallerThan"></wecpof:IntSmallerThan>
  <Style x:Key="CoverWeeksStyle.ElementStyle.DataGridTextColumn">
    <Setter Property="TextBlock.Background" Value="Transparent"></Setter>
    <Setter Property="TextBlock.HorizontalAlignment" Value="Right" />
      <DataTrigger Binding="{Binding Path=CoverWeeks,
Converter={StaticResource IntSmallerThan},ConverterParameter=4}" Value="True"> <Setter Property="TextBlock.Background" Value="Pink"></Setter> <Setter Property="TextBlock.HorizontalAlignment" Value="Right" /> <Setter Property="TextBlock.Margin" Value="0,4,0,0"/> <Setter Property="TextBlock.FontWeight" Value="Bold"/> </DataTrigger> </Style.Triggers> </Style>


In the style definition a DataTrigger is added. The DataTrigger watch the ViewModel attribute CoverWeeks:int – it use a IValueConverter that I called IntSmallerThan – that checks if the value watched is smaller than the value in ConverterParameter. If so then true and the style is changed with the contents of the DataTrigger.

In my case I should mark cells with a value lower than 4 in pink:


This entry was posted in ViewModel, WECPOF, WPF and tagged . Bookmark the permalink.

Leave a Reply

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