Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting DataContext on DataGrid.RowStyle

Using the following sample R# (resharper) is not able to find the datacontext of the Row style and warns about a wrong binding (at runtime works fine). Seems like the Style is not getting the DataContext of the ItemsSource:

enter image description here

MainWindow.xaml:

<Window x:Class="TestDatacontext.MainWindow"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:testDatacontext="clr-namespace:TestDatacontext"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

    mc:Ignorable="d"

    d:DataContext="{d:DesignInstance testDatacontext:MainWindowVM}"  >

<DataGrid ItemsSource="{Binding Items}" >
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow" >
            <Setter Property="Header" Value="{Binding Name}" />
        </Style>
    </DataGrid.RowStyle>
</DataGrid>
</Window>

MainWindowVM:

using System.Collections.ObjectModel;

namespace TestDatacontext
{
    class MainWindowVM
    {
        public ObservableCollection<ItemVM> Items { get; private set; }
    }
}

ItemVM:

namespace TestDatacontext
{
    class ItemVM
    {
        public string Name { get; set; }
    }
}
like image 539
Ignacio Soler Garcia Avatar asked Nov 21 '12 11:11

Ignacio Soler Garcia


1 Answers

You are correct, ReSharper has no knowledge about how RowStyle will be used in this particular control (is it style per every item of ItemsSource? or some kind of header style and bindings will have access to ItemsSource object itself?), so it stops traversing tree looking for DataContext type on Style declaration.

This issue can be solved with additional annotation on Style declaration:

<Style TargetType="DataGridRow" d:DataContext="{d:DesignInstance vms:ItemVM}">
  <Setter Property="Header" Value="{Binding Name}" />
</Style>

Project will compile fine, VS designer and R# will work, but VS xaml support will produce 1 error in errors window - "Property 'DataContext' is not attachable to elements of type 'Style'". That's a bit annoying, but works. Other way is to quilify property type like this:

<Style TargetType="DataGridRow">
  <Setter Property="Header" Value="{Binding (vms:ItemVM.Name)}" />
</Style>

But it produces VS xaml support error too :) and have slightly different behavior in runtime - this binding will work only with Name property of ItemVM type and will not work if somehow VM object will be replaced with some other object of different type with Name property at runtime (so binding became "strongly-typed").

We are still looking for a better way to solve this kind of problems in ReSharper 8.0 and make VS designer happy, sorry for confusing!

like image 153
controlflow Avatar answered Sep 21 '22 16:09

controlflow