【问题标题】:WPF DataGrid: How do I access the DataRow a TextBox etc. resides in?WPF DataGrid:如何访问 TextBox 等所在的 DataRow?
【发布时间】:2011-06-17 15:31:45
【问题描述】:

所以我有这样定义的列:

                        <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) 刷新 Style 再次检查 RowState:

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

显然它会比这更通用。

编辑 2:这显然行不通,因为我需要单独重置每个控件的样式,即使有可能这样做也是一件坏事

【问题讨论】:

  • 你确定是RelativeSource绑定的问题吗?可能是 DataGridRow.Row.RowState 不可访问,或者 RowState 是一个与字符串进行比较的枚举,因此总是返回 false。我喜欢使用的一个简单测试是将 ToolTip 设置为 RelativeSource 以查看是否出现任何问题。

标签: c# wpf xaml datagrid


【解决方案1】:

请参阅以下内容:

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

就绑定而言,Row 不是DataGridRow 的属性,所以你必须使用DataContext.Row.RowState

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

【讨论】:

  • 谢谢杰森。由于难以检测 RowState 的变化,我选择使用事件来“刷新”样式。更新了我的帖子以反映我所寻求的解决方案。
【解决方案2】:

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

【讨论】:

  • DataGridCell 中没有 'Row' 属性,在寻找 TextBox 的父级时也有同样的问题。
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多