0

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.

1 Answers1

1

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.

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
  • Thank you for your quick response. I am new to WPF, I come from the Win Forms world. Wasn't sure if there was some way to bind a TextBox's text property to a calculation of other TextBoxes on the window. – Gabriel Montanaro Jun 14 '12 at 15:24
  • @GabrielMontanaro: You can create data bindings between controls because the `TextBox.Text` property is a dependency property that interacts with the binding framework and sends notifications when it is changed. However, you seem to be binding directly to the `DataContext` which then has to implement a way to notify the data binding framework of changes. – Martin Liversage Jun 14 '12 at 15:31