【问题标题】:Custom DatagridTemplateColumn button - Bind button content to custom column property自定义 DatagridTemplateColumn 按钮 - 将按钮内容绑定到自定义列属性
【发布时间】:2020-05-11 10:14:03
【问题描述】:

我想创建一个带有按钮的自定义数据网格列。我希望它可重用,所以我不想在模板中定义按钮的文本,而是在列的依赖属性(ButtonText as string)中定义。

这是我目前的代码(不工作)

<DataGridTemplateColumn x:Class="RafColumnButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyProject"
             mc:Ignorable="d"  CanUserResize="False">

    <DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <Button Content="{Binding ButtonText, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=local:RafColumnButton}}"/>
        </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>

</DataGridTemplateColumn>

我认为它与datacontext有关,但我是wpf的新手。

编辑:这是依赖属性的 rafcolumnButton 代码隐藏

Public Property ButtonText As String
    Get
        Return GetValue(ButtonTextProperty)
    End Get

    Set(ByVal value As String)
        SetValue(ButtonTextProperty, value)
    End Set
End Property

Public Shared ReadOnly ButtonTextProperty As DependencyProperty =
                       DependencyProperty.Register(NameOf(ButtonText),
                       GetType(String), GetType(RafColumnButton),
                       New PropertyMetadata(""))

【问题讨论】:

    标签: wpf xaml binding


    【解决方案1】:

    DataGridTemplateColumn.CellTemplateDataContext 是当前数据项。

    如果DataGrid.ItemsSource 包含具有ButtonText 属性的数据项,则以下绑定将起作用:

    <DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
        <Button Content="{Binding ButtonText}"/>
      </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    

    备注
    一般来说,您不能绑定到DataGridTemplateColumnDataGridColumn。这是因为DataGridColumn 不是从Visual 派生的,因此不能成为可视树的一部分。只有派生自抽象类Visual(如UIElement)的类型才能成为可视化树的一部分。只有派生自FrameworkElement 的类型才能成为逻辑树的一部分。见Microsoft Docs: Trees in WPF

    DataGridColumn 可以被视为构成列和单元格的实际控件的占位符。

    【讨论】:

    • 是的,我知道。我还有其他列(图像)可以这样工作。但我想绑定 datagridcolumn 本身的 ButtonText 属性(它是文本类型的自定义依赖属性),我将用它来编辑我的问题。
    • 查看我的回答。这应该澄清一些事情。
    • 我真的很难过。我在数据网格上创建了​​该属性,它可以工作,但这意味着我只能通过数据网格使用该类型的列。如果有其他方法...
    • 请再来。您已经在自定义 DataGrid 上创建了 ButtonText 属性?您当然可以绑定到父 DataGrid。这是你想要的吗?我知道这个属性是在自定义 DataGridColumn 上定义的。
    • 不,我想要列本身的属性。但正如你所建议的,我尝试(只是为了尝试)在数据网格上创建它并且它可以工作。但这不是我想要的,因为有了这个,我可以在数据网格中只有一个这种类型的列(或更多,但具有相同的文本)。另一种可能的解决方案是在数据源本身上创建一个带有按钮文本的只读属性。但我不太喜欢这种解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多