【问题标题】:WPF DataGrid - binding together controls of different DataGridTemplateColumnWPF DataGrid - 将不同 DataGridTemplateColumn 的控件绑定在一起
【发布时间】:2013-11-18 07:44:35
【问题描述】:

我正在尝试将不同 DataGridTemplateColumns 的控件绑定在一起。举个例子:

        DataGridTemplateColumn col1 = new DataGridTemplateColumn();
        col1.Header = "Source";
        FrameworkElementFactory factory1 = new FrameworkElementFactory(typeof(CheckBox));
        Binding b1 = new Binding(".");
        factory1.SetValue(CheckBox.IsCheckedProperty, b1);
        DataTemplate cellTemplate1 = new DataTemplate();
        cellTemplate1.VisualTree = factory1;
        col1.CellTemplate = cellTemplate1;
        dataGrid1.Columns.Add(col1);

        DataGridTemplateColumn col2 = new DataGridTemplateColumn();
        col2.Header = "Binded to Source";
        FrameworkElementFactory factory2 = new FrameworkElementFactory(typeof(TextBox));
        Binding b2 = new Binding("What goes here?");
        factory2.SetValue(TextBox.IsEnabledProperty, b2); //Enable TextBox if CheckBox of col1 is checked
        DataTemplate cellTemplate2 = new DataTemplate();
        cellTemplate2.VisualTree = factory2;
        col2.CellTemplate = cellTemplate2;
        dataGrid1.Columns.Add(col2);

        dataGrid1.ItemsSource = new bool[] { true, false };

我想将一个控件的属性(本例中为 CheckBox)绑定到不同 DataGridTemplateColumn 中另一个控件的属性。有可能吗?此绑定是严格的 UI 事物,不会反映在视图模型中。

【问题讨论】:

  • b1 绑定有什么用?
  • b1 将 col1 的 CheckBox 的 IsChecked 属性绑定到模型(本例中为布尔数组)。这工作正常。问题在于 b2 绑定 - 如何绑定到另一列的控件,而不是模型?

标签: c# wpf datagrid


【解决方案1】:

WPF Datagrid 是面向对象的,因此行中的单元格控件之间的绑定不是做事的自然方式。 正如您所说,您对 Checkbox 的绑定 b1 使用模型中的属性,所以我建议您将 Textbox (b2) 的 IsEnabled 绑定到同一属性。

无论如何,如果您坚持以另一种方式进行,您的 b2 绑定应该使用FindAncestor 来获取其中包含的DataGridRow,然后在DataGridRow.ItemsPanel 中挖掘以找到复选框。这并不简单,对我来说,这是一个 hack。

【讨论】:

    猜你喜欢
    • 2010-10-10
    • 2014-06-12
    • 2023-03-18
    • 2016-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多