开发者

Setting XAML Datagrid Text colour per row

开发者 https://www.devze.com 2023-02-12 08:48 出处:网络
I am trying to add validation to a datagrid in XAML. Currently, I have created a method which checks 3 textboxes for valid input and if false sets a value in the collection the datagrid is bound to,

I am trying to add validation to a datagrid in XAML.

Currently, I have created a method which checks 3 textboxes for valid input and if false sets a value in the collection the datagrid is bound to, to either true or false. This part works fine.

The problem I am now having is making this actually work.

I have created a converter :

 public override object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
     bool isRowValid = ((bool)value);

     ConsoleColor validColour = ConsoleColor.Green;
     ConsoleColor invalidColour = ConsoleColor.Red;

     if (isRowValid)
     {
        return validColour;
     }
     else
     {
        return invalidColour;
     }
  }

So开发者_开发技巧 when the row is invalid it will display red, when valid it will display green.

The method to validate each row gets called when the row looses focus, and by default each row is set to invalid.

I have been attempting to set the background for each row by doing

<DataGrid.RowBackground>
    <SolidColorBrush Color="{Binding Path=IsRowValid, Converter={StaticResource RowValidConverter}}" />
</DataGrid.RowBackground>

but ideally, I would like this to only adjust the text colour and not the background.

Any suggestions on how to implement this would be greatly appreciated,

Thanks.


If I understand your problem correctly then I think an easier approach is to add a Trigger for Validation.HasError in the RowStyle

<DataGrid ...>
    <DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="TextElement.Foreground" Value="Green"/>
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="True">
                    <Setter Property="TextElement.Foreground" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </DataGrid.RowStyle>
    <!--...-->
</DataGrid>

Or if you're controling this some other way with a Property called IsRowValid in your ViewModel then you can just change the Trigger to a DataTrigger

<DataTrigger Binding="{Binding IsRowValid}" Value="True">
    <Setter Property="TextElement.Foreground" Value="Red"/>
</DataTrigger>
0

精彩评论

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