开发者

WPF DataGrid: How do I access the DataRow a TextBox etc. resides in?

So I have columns defined like this:

                        <DataGridTemplateCo开发者_运维技巧lumn.CellTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Path=COLUMN_NAME, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>

TextBox isn't the only control that may exist in the DataTemplate for a column, I have DateTimePickers, ComboBoxes, etc.

And what I want to do is define some style triggers like this that access some property in the 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>

Now unfortunately it would appear the TextBoxes are never logical children of DataGridRows. So what is the solution? Of course I can create a trigger that targets DataGridRows themselves, but this is redundant because setting the foreground property will do nothing (TextBoxes and other controls sit in front).

Any help most appreciated. Fugu

EDIT: Here is the solution I chose, because RowState does not notify its listeners and extending DataRow is problematic.

1) Bind an event to the control(s) for when their data changes. 2) Refresh the Style to check for the RowState again:

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

Obviously it will be made more generic than that.

edit 2: This blatantly won't work as I'd need to reset the style for each control individually, which even if it was possible would be a bad thing to do


See the following:

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

As far as the binding, Row isn't a property of DataGridRow, so you have to use DataContext.Row.RowState.

With that said, WPF is unable to detect changes to the RowState property, so your best bet is probably to wrap your items in a view model, rather than directly binding to the DataTable.


What you want is DataGridCell, which can be styled. From memory the properties -should- be passed down to the TextBox


Try using a data template selector. Create different data templates that contain your desired properties paired with text boxes and swap them around inside your data grid. http://msdn.microsoft.com/en-us/library/system.windows.controls.datatemplateselector.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜