wpf - 我可以在 Xaml 中指定 DataGrid 项目的类型吗?

标签 wpf xaml resharper

在 Xaml 中创建数据模板时,我可以指定 DataTemplate 将应用到的项目的类型,如下所示:

<DataTemplate DataType="{x:Type Vehicle}">
  <!-- do some stuff with the Vehicle class's properties -->
</DataTemplate>

我希望在创建 DataGrid 时能够执行相同的操作,但这不是 DataType 属性的选项:

<DataGrid ItemsSource="{Binding Cars}" DataType="{x:Type Vehicle}">
     <!-- Create columns that bind to the Vehicle class's properties -->
</DataGrid>

一个相当糟糕的解决方法是在每一列上单独执行此操作:

<DataGrid ItemsSource="{Binding Cars}" DataType="{x:Type Vehicle}">
  <DataGrid.Columns>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.Header />
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate DataType="{x:Type Vehicle}">
          <!-- bind to a Vehicle class property -->
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.Header />
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate DataType="{x:Type Vehicle}">
          <!-- bind to a Vehicle class property -->
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTemplateColumn>
      <DataGridTemplateColumn.Header />
      <DataGridTemplateColumn.CellTemplate>
        <DataTemplate DataType="{x:Type Vehicle}">
          <!-- bind to a Vehicle class property -->
        </DataTemplate>
      </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
  </DataGrid.Columns>
</DataGrid>

有没有更好的方法来做到这一点我不知道?如果我不这样做,ReSharper 的各个部分就无法很好地应对。

最佳答案

试试这个:

<DataGrid ItemsSource="{Binding Cars}"
          d:DesignSource="{d:DesignInstance Type={x:Type Vehicle}, CreateList=True}">
     <!-- Create columns that bind to the Vehicle class's properties -->
</DataGrid>

关于wpf - 我可以在 Xaml 中指定 DataGrid 项目的类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13877999/

相关文章:

wpf - Prism中这两种加载模块的方式有什么区别?

.net - WPF弹出窗口的习惯

Resharper Test Runner 抢夺焦点

c# - 将 DataGrid 的一部分从表单传递到另一个表单(有条件)

WPF 按钮样式未应用于子元素

WPF:如何删除切换按钮的聚焦动画?

c# - 我们可以知道窗口是否已被用户或 WPF 上的代码关闭吗?

c# - Areo Glass Effect 和 windowStyle 设置为 none 会导致窗口调整大小无法正常运行

VS2012 上的 Resharper 7 忽略 app.config 中的程序集重定向

C# is operator with nullable types always false 根据 ReSharper