我该如何告诉Resharper ICollectionView所包含的类型?

5

I have the following XAML:

<DataGrid ItemsSource="{Binding Path=FilteredPatients}" SelectedItem="{Binding Path=SelectedPatient}">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name"
                            Binding="{Binding Path=FormattedName}" />
        <DataGridTextColumn Header="Date of Birth"
                            Binding="{Binding Path=BirthDate} />
        <DataGridTextColumn Header="Gender" 
                            Binding="{Binding Path=Gender} />
        <DataGridTextColumn Header="Id"
                            Binding="{Binding Path=Id}" />
    </DataGrid.Columns>
</DataGrid>

根据父控件的DataContext,Resharper确定FilteredPatients和SelectedPatient是可以使用的。然而,FilteredPatients是一个ICollectionView,因此Resharper无法确定它包含的是Patient实例,而该实例具有DataGrid列绑定中指定的属性。

在运行时一切都正常,那么我如何告诉Resharper FilteredPatients所包含的项的类型呢?


这个回答解决了你的问题吗?Wpf ICollectionView绑定项无法解析对象类型的属性 - Maxence
3个回答

3
最简单的解决方案是禁用Resharper对这些列的错误提示,因为它在这个问题上是不正确的:
<!-- ReSharper disable Xaml.BindingWithContextNotResolved -->
<DataGridTextColumn />
<DataGridTextColumn />
<!-- ReSharper restore Xaml.BindingWithContextNotResolved -->

使用DataGridTemplateColumn而不是DataGridTextColumn是一个真正的解决方案。这样做可以让你在每列的DataTemplate中标识出DataType,但需要更多的xaml代码:

<DataGrid ItemsSource="{Binding Path=FilteredPatients}" SelectedItem="{Binding Path=SelectedPatient}">
    <DataGrid.Columns>
        <DataGridTemplateColumn Header="Name">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate DataType="namespace:Patient">
                    <TextBlock Text={Binding FormattedName} />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

我不想禁用警告,这就是我的问题所在。第二种解决方案的问题在于它使XAML变得更长。我希望有一种方法可以在一行中简单地告诉Resharper包含的对象是什么。 - 17 of 26
另一种通常可以做到的方法是在DataGridTextColumns上单独设置d:DataContext(我假设您已经为整个视图完成了此操作),但据我所知,在这种情况下,这种方法不起作用。当我调查此问题时,我尝试过这样做,但Resharper仍然不喜欢它。但您可以尝试使用它,并且也许有办法使其正常工作。 - JNP

1

1
三年过去了,它仍然没有被修复。我认为JNP的答案是这里唯一真正的选择。 - Bijington
是的,这就是我在等待修复时一直在做的事情 :( - 17 of 26
我也偶然发现了在此处实现通用ICollectionView<T>的方法:https://benoitpatra.com/2014/10/12/a-generic-version-of-icollectionview-used-in-a-mvvm-searchable-list/ 然而,当我们动态开启/关闭分组时,在我们的情况下会引起问题。 - Bijington

0

由于这是设计时间,而Resharper让它知道的一种方法是在顶部设置DesignInstance,如下所示:

d:DataContext="{d:DesignInstance {x:Type viewModels:MyViewModel}}"

这不会影响生产,但会让 Resharper 反映您的 ViewModel 中的值。


我已经做了这个,这就是为什么DataGrid本身的绑定是正确的(正如我在问题中提到的)。问题在于ICollectionView公开了一个没有类型的IEnumerable,因此Resharper不知道FilteredPatients包含的类型。 - 17 of 26

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接