Question

I currently use the following method to set the colour of my Row Background.

XAML

        <Style TargetType="{x:Type xcdg:DataRow}">
            <Setter Property="Background">
                <Setter.Value>
                    <MultiBinding Converter="{StaticResource colorConverter}">
                        <Binding RelativeSource="{RelativeSource Self}" Path="IsSelected"/>
                        <Binding BindsDirectlyToSource="True" />
                    </MultiBinding>
                </Setter.Value>
            </Setter>
        </Style>

C#

public class ColourConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var isRowSelected = (bool)values[0];
        var myInstance = (MyClass) values[1];

        // Return default
        if (isRowSelected || myInstance == null)
            return DependencyProperty.UnsetValue;

        // Get the check for the current field
        return GetColour(myInstance) ?? DependencyProperty.UnsetValue;
    }

    private static SolidColorBrush GetColour(MyClass myInstance)
    {
        if (heartbeat == null)
        {
            return null;
        }

        // Is it more two minutes old?
        return (myInstance.CreatedDateTime + TimeSpan.FromMinutes(2) < Clock.UtcNow())
                   ? Brushes.LightPink
                   : Brushes.LightGreen;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException(this.GetType().Name + " cannot convert back");
    }
}

The problem is that this Converter is only called on population of the DataRow with new values. What I really need is some sort of callback to change the colour after a certain time or to have the Converter reevaluated periodically.

The colour update doesn't have to be instant, just within a few seconds. If I have a callback for each row then I'd need as many threads to match (They are created and hence expire (which changes their colour) at different times), with ~1000 rows this doesn't seem like an efficient option.

The other option is to poll the rows on one thread periodically and reevaluate the converter on each iteration (Every 5 seconds?). I think this is likely the way to go but I don't know how to go about it in WPF.

Perhaps there's another approach or built in support for such a task?

Thanks in advance!

Was it helpful?

Solution

Should be possible to get the BindingExpression from the DataRow and simply call UpdateSource/UpdateTarget manually as many times as you need...

BindingExpression binding = Control.GetBindingExpression(DataRow.BackgroundProperty)
binding.UpdateSource;

Don't forget to also change the UpdateSourceTrigger property on the binding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top