【问题标题】:Custom WPF DataGrid Column自定义 WPF 数据网格列
【发布时间】:2011-10-31 15:37:42
【问题描述】:

我在过去一周左右尝试为 wpf 数据网格制作自定义列

重点是我在整个应用程序的多个数据网格中显示某些类型的数据,我不想每次都重新声明所有属性

这里是一些反复使用的代码示例

<DataGridComboBoxColumn SelectedValueBinding="{Binding PersonID}" SelectedValuePath="PersonID" DisplayMemberPath="PersonName" Header="Customer" ItemsSource="{Binding Source={StaticResource PersonSource}}" />

所以我尝试制作这样的用户控件

Public Class PersonColumn
Inherits DataGridComboBoxColumn
Sub New()
    SelectedValuePath = "PersonID"
    DisplayMemberPath = "PersonName"
    Header = "Customer"
End Sub
End Class

这是一个帮助,但并不完整,因为

  1. 我不能做任何样式或其他标记工作
  2. 我似乎无法使用 FindResource 命令获取 PersonSource

如何改进?我所有的搜索都显示 xaml redone 一次又一次,这似乎很多余

同时我试图创建一个日期选择器列,但找不到任何可重用列的样本,只是再次在每个数据网格中重新定义

非常感谢

编辑

我现在正在尝试一个完全不同的方向

我用以下标记制作了一个用户控件

<DataGridTemplateColumn Header="Date" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"      xmlns:my="clr-namespace:SampleWpf"  x:Class="DateColumn">
<DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
        <TextBlock Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:DateColumn}}, Path=Value}" />
    </DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
    <DataTemplate>
        <DatePicker SelectedDate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type my:DateColumn}}, Path=Value}"  />
    </DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>

还有一些代码隐藏

Public Class DateColumn
Inherits DataGridTemplateColumn
Public Shared ReadOnly ValueProperty = DependencyProperty.Register("Value", GetType(Date?), GetType(DateColumn))
Property Value As Date?
End Class

但这不起作用。日期未显示在列中,我的更改也未保存回数据源

datagrid xaml 非常简单

                <my:DateColumn   Value="{Binding Path=ReceivedOn}" Header="ReceivedOn" />

你们都是怎么做这些事情的? 谢谢十亿!

【问题讨论】:

    标签: wpf datagrid user-controls


    【解决方案1】:

    您应该能够在应用程序的资源中创建一个可重用的DataTemplate,然后只需添加一个带有指定CellTemplate 的DataGridTemplateColumn

    <DataGridTemplateColumn CellTemplate="{DynamicResource CustomColumnTemplate}" />
    

    【讨论】:

    • 谢谢。但是如果我想在我的列中添加自定义属性,我该怎么做?即我想添加一个 MinAge 属性,我可以设置 MinAge="10" 然后该列将仅显示 10 岁以上的人。我可能还需要一些编码。我不能在资源中完成所有这些,可以吗?谢谢!
    • @Yisman 对 DataGrid 的 ItemSource 应用过滤器会更好
    • 我的意思是过滤组合框结果
    • 嗨。有人对我有什么想法吗?我相信你们都在为这些情况使用某种解决方案;-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2011-11-08
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多