【问题标题】:Setting DataContext on DataGrid.RowStyle在 DataGrid.RowStyle 上设置 DataContext
【发布时间】:2012-11-09 15:59:45
【问题描述】:

使用以下示例 R# (resharper) 无法找到 Row 样式的数据上下文并警告错误绑定(在运行时工作正常)。似乎 Style 没有获取 ItemsSource 的 DataContext:

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>

主窗口虚拟机:

using System.Collections.ObjectModel;

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

项目虚拟机:

namespace TestDatacontext
{
    class ItemVM
    {
        public string Name { get; set; }
    }
}

【问题讨论】:

    标签: c# .net wpf mvvm resharper


    【解决方案1】:

    你是对的,ReSharper 不知道RowStyle 将如何在这个特定控件中使用(它是ItemsSource 的每个项目的样式吗?或者某种标题样式和绑定可以访问ItemsSource对象本身?),因此它停止遍历树来查找 Style 声明上的 DataContext 类型。

    可以通过在Style 声明上添加注释来解决此问题:

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

    项目可以正常编译,VS 设计器和 R# 可以工作,但 VS xaml 支持会在错误窗口中产生 1 个错误 - “属性 'DataContext' 不能附加到 'Style' 类型的元素”。这有点烦人,但有效。其他方法是像这样对属性类型进行 quilify:

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

    但它也会产生 VS xaml 支持错误 :) 并且在运行时的行为略有不同 - 此绑定仅适用于 ItemVM 类型的 Name 属性,并且如果以某种方式将 VM 对象替换为其他对象,则此绑定将不起作用在运行时具有 Name 属性的不同类型的对象(因此绑定变为“强类型”)。

    我们仍在寻找更好的方法来解决 ReSharper 8.0 中的此类问题,并让 VS 设计人员感到高兴,很抱歉造成混淆!

    【讨论】:

    • 感谢您的澄清,但是...我看不到 ItemsSource == 1 Row 的关系 1 项在哪里无效,如果是,您可以将 RowStyle 的 DataContext 设置为每一行之一你不能吗?
    • ReSharper 不知道 Row 的语义是什么以及 如何 控件将使用该样式(或者是否会使用它?)。就像这里一样,R# 不知道 ColumnHeaderStyle 是什么以及它与包含控制的 ItemsSource 的关系:gist.github.com/4125475
    • 是我必须使用的。
    • 这方面有进展吗? ;-)
    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2010-11-24
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多