WPF DataGrid:如何访问TextBox等所在的DataRow?

时间:2011-06-17 15:31:46

标签: c# wpf xaml datagrid

所以我的列定义如下:

                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=COLUMN_NAME, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>

TextBox不是DataTemplate中可能存在的唯一控件,我有DateTimePickers,ComboBoxes等。

我想要做的是定义一些样式触发器来访问DataRow中的一些属性:

            <Style TargetType="{x:Type TextBox}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding  RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGridRow}}, 
                        Path=Row.RowState}" Value="Modified">
                        <Setter Property="Foreground" Value="LightGreen" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>

现在不幸的是,TextBoxes似乎永远不是DataGridRows的逻辑子代。那么解决方案是什么?当然,我可以创建一个以DataGridRows为目标的触发器,但这是多余的,因为设置前景属性将不执行任何操作(TextBoxes和其他控件位于前面)。

最值得赞赏的任何帮助。 河豚

编辑:这是我选择的解决方案,因为RowState不通知其侦听器,并且扩展DataRow是有问题的。

1)将事件绑定到控件,以确定其数据何时发生变化。 2)刷新样式以再次检查RowState:

        Style s = ((TextBox)sender).Style;
        ((TextBox)sender).Style = null;
        ((TextBox)sender).Style = s;

显然它会比那更通用。

编辑2:这显然不起作用,因为我需要单独重置每个控件的样式,即使可能会做坏事

3 个答案:

答案 0 :(得分:1)

你想要的是DataGridCell,可以设置样式。从内存中,属性 - 应该传递给TextBox

答案 1 :(得分:1)

请参阅以下内容:

https://stackoverflow.com/questions/4947918/wpftoolkit-datagrid-highlight-modified-rows

就绑定而言,Row不属于DataGridRow的属性,因此您必须使用DataContext.Row.RowState

话虽如此,WPF无法检测到RowState属性的更改,因此最好的办法是将项目包装在视图模型中,而不是直接绑定到DataTable。

答案 2 :(得分:0)

尝试使用数据模板选择器。创建包含与文本框配对的所需属性的不同数据模板,并在数据网格内交换它们。 http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx