WPF DataGrid - 将不同DataGridTemplateColumn的控件绑定在一起

时间:2013-11-18 07:44:35

标签: c# wpf datagrid

我正在尝试将不同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事物,不会反映在视图模型中。

1 个答案:

答案 0 :(得分:1)

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

无论如何,如果你坚持用另一种方式做,那么你的b2绑定应该使用FindAncestor来获取其中包含的DataGridRow,然后挖掘DataGridRow.ItemsPanel以找到复选框。这不是直截了当的,对我来说,这是一个黑客。

相关问题