Gabriel Montanaro
Gabriel Montanaro

Reputation: 47

Creating a dynamic calculated field in WPF

I am trying to create a series of dynamic, calculated fields on my window.

Right now I have it working when the form loads as follows...

<Window.Resources>
    <src:PaymentVarianceConverter x:Key="PaymentConverter" />
</Window.Resources>

<TextBlock Text="{Binding Path=., Converter={StaticResource PaymentConverter}, 
                  ConverterParameter=CASH, StringFormat={}{0:C}, Mode=OneWay}"/>
<TextBlock Text="{Binding Path=., Converter={StaticResource PaymentConverter}, 
                  ConverterParameter=CHECK, StringFormat={}{0:C}, Mode=OneWay}"/>

here is the converter:

public sealed class PaymentVarianceConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is Route))
            return null;
        var route = value as Route;

        switch (parameter.ToString())
        {
            case "CASH":
                return route.CashTotal - route.TotalExpectedCash;
            case "CHECK":
                return route.CheckTotal - route.TotalExpectedCheck;
            default:
                return null;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException("ConvertBack Not implemented");
    }
}

All this works great, except it won't refresh when the underlying values (i.e. route.CashTotal) change.

Is there any way I can get this to dynamically refresh? I'd like to avoid making them properties on my source object and calling OnPropertyChanged() for each of them as there are many of them.

Upvotes: 0

Views: 749

Answers (1)

Martin Liversage
Martin Liversage

Reputation: 106926

Data binding requires to be notified when the bound value changes. You will have to implement INotifiyPropertyChanged to do this. (Or dependency properties, but that requires more work on your behalf.) WPF does not have psychic powers unfortunately.

Upvotes: 1

Related Questions