Search code examples
c#.netwpfxamltelerik

Conditional background on GridViewRow based on textbox value next to DataGrid


HOW do I pass the value of the TextBox to the StyleSelector so I can return the correct Style?

I want to be able to choose the background of a row conditionally by comparing a property of the object shown in the row with the value of an input control (e.g TextBox).

I made a StyleSelector class containing two styles and a property to contain the value of the TextBox.

    public class OutOfBoundsRowStyleSelector : StyleSelector
{
    public double FilterValue { get; set; }
    public Style DefaultStyle { get; set; }
    public Style OutOfBoundsStyle { get; set; }


    public override Style SelectStyle(object item, DependencyObject container)
    {

        // Compare FilterValue to property of item  and return the appropriate style here.

        return DefaultStyle; 

    }
}

I added a TextBox and bound the Value to a property in the ViewModel like so.

<TextBox x:Name="txtBoundsFilter" Text="{Binding BoundsFilter}"/>

I filled these styles in xaml & tried to bind the TextBox value to the property in the StyleSelector class.

            <Classes:OutOfBoundsRowStyleSelector x:Key="OutOfBoundsRowStyleSelector">
            <Classes:OutOfBoundsRowStyleSelector.DefaultStyle>
                <Style TargetType="telerik:GridViewRow">
                    <Setter Property="Background" Value="White"/>
                </Style>
            </Classes:OutOfBoundsRowStyleSelector.DefaultStyle>
            <Classes:OutOfBoundsRowStyleSelector.OutOfBoundsStyle>
                <Style TargetType="telerik:GridViewRow">
                    <Setter Property="Background" Value="Red" />
                </Style>
            </Classes:OutOfBoundsRowStyleSelector.OutOfBoundsStyle>
            <Classes:OutOfBoundsRowStyleSelector.FilterValue>
                <Binding  Path="BoundsFilter" Mode="TwoWay"/>
            </Classes:OutOfBoundsRowStyleSelector.FilterValue>
        </Classes:OutOfBoundsRowStyleSelector>

Finally I added the RowStyleSelector to the DataGrid.

            <telerik:RadGridView x:Name="dataGrid" ItemsSource="{Binding BatchList} RowStyleSelector="{StaticResource OutOfBoundsRowStyleSelector}"  >

Unfortunately, you cannot use a binding like that. I got the following error message:

A 'Binding' cannot be set on the 'FilterValue' property of type 'OutOfBoundsRowStyleSelector'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.


Solution

  • I added an extra property to the item model. Then whenever I refresh the grid, I fill in the value of the TextBox in each item. This way I can access the value through the item parameter from the GetStyle() method. This doesn't seem like the most elegant way, but it did the job for me.