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:
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; }
}
}
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With