【问题标题】:What is the code behind for datagridtemplatecolumn, and how to use it?datagridtemplatecolumn 背后的代码是什么,如何使用?
【发布时间】:2010-12-17 19:08:29
【问题描述】:

我在 WPF 中有一个 DataGrid。在绑定到特定的ItemsSource 之后,我正在尝试将Buttons 添加到网格的某些单元格中。我曾尝试在 xaml 中这样做:

<dg:DataGridTemplateColumn x:Name="R1" CanUserReorder="False" IsReadOnly="False">             
    <dg:DataGridTemplateColumn.CellTemplate>
        <DataTemplate>
            <awc:ImageButton Content="Edit" Name="btnEdit" Visibility="Collapsed"/>
        </DataTemplate>
    </dg:DataGridTemplateColumn.CellTemplate>
</dg:DataGridTemplateColumn>

但是,我想知道如何在后面的代码中做到这一点。我需要这个,以便在发生特定点击时可以放置Buttons。任何帮助将不胜感激。

【问题讨论】:

    标签: wpf datagrid datagridtemplatecolumn


    【解决方案1】:

    使用这个:

    DataGridTemplateColumn col1 = new DataGridTemplateColumn();
    col1.Header = "MyHeader";
    FrameworkElementFactory factory1 = new FrameworkElementFactory(typeof(CheckBox));
    Binding b1 = new Binding("IsSelected");
    b1.Mode = BindingMode.TwoWay;
    factory1.SetValue(CheckBox.IsCheckedProperty, b1);
    factory1.AddHandler(CheckBox.CheckedEvent, new RoutedEventHandler(chkSelect_Checked));
    DataTemplate cellTemplate1 = new DataTemplate();
    cellTemplate1.VisualTree = factory1;
    col1.CellTemplate = cellTemplate1;
    dgTransportReqsts.DataGrid.Columns.Add(col1);
    

    我使用它在运行时在我的 DataGridTemplateColumn 中添加 CheckBox。 希望这会有所帮助!

    【讨论】:

    • 很抱歉碰到了一个旧线程,但如果是 FrameworkElementFactory(typeof(Button)) 的按钮,我该如何添加按钮文本?我一直无法这样做,还是我错过了什么?
    • @Manish Sinha,使用 factory1.SetValue(Button.ContentProperty, b1);您可以在您的情况下设置 Button 的任何属性,就像我在上面的示例中设置 CheckBox 的 IsChecked 属性一样。
    • 甜蜜!这么简单!!非常感谢。
    【解决方案2】:

    如果您想在网格实例化之前添加按钮,Anurag 的回答对您来说非常有用,特别是在您将列添加到网格之前。

    如果您想在在网格已经构建之后将按钮添加到网格单元格中,您可以通过更改 DataGridCell 对象来实现。首先你必须找到它:

    1. 使用DataGridColumn.GetCellContent 查找DataGridCell
    2. 使用VisualTreeHelper 向上扫描可视化树到DataGridCell

    完成此操作后,有多种方法可以将按钮添加到 DataGridCell,具体取决于您要实现的目标:

    • DataGridCell.Template 设置为包含所需按钮和其他样式的ControlTemplate,-或-
    • DataGridCell.ContentTemplate 设置为包含所需按钮和其他项目的DataTemplate,-或-
    • 让您的专栏的DataTemplate 包含一个占位符面板来保存新按钮,通过Name 在可视化树中搜索此面板,然后将您的按钮添加到其中。

    另一种不需要查找单元格的方法是:

    1. 在您的视图模型中包含一个 ObservableCollection&lt;T&gt; 属性,该属性提供创建按钮的信息
    2. 在您的DataTemplate 中包含一个引用此属性的ItemsControl,并有一个DataTemplate 可以创建T 类型之外的正确按钮
    3. 当你想添加一个按钮时,只需在ObservableCollection属性中添加一个项目

    【讨论】:

      猜你喜欢
      • 2011-02-06
      • 2013-08-21
      • 2014-10-17
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多