简体   繁体   中英

WPF Binding to ViewModel and update of view

I would like to bind to my complete ViewModel because two properties of the ViewModel are needed for the converter to decide on there color.

{Binding Converter={StaticResource ErrorCountToSignalColorConverter}

With this the converter gets the ViewModel and can read two properties (ErrorCount and HasReceivedData). But when one of the properties changes the binding is not updated. Of course both properties have a OnPropertyChange() raised.

How can I achieve the view to be updated (with the correct color) when one of both properties is changed?

You need to choose multibinding using MultiValueConverter in this case. It will bind multiple properties ( ErrorCount , and HasReceivedData ) to the View and any change in any property will be reflected.

MSDN simplistic example - Multibinding

You could pass both properties from the view using a MultiBinding, but then the dependency between ErrorCount/HasReceivedData/Signal leaks into the UI code (and needs to be repeated each time it is used). One of the main goals of a view model is to allow the view to be separated from details like this.

I suggest to use an enum to represent the set of possibilities:

public enum SignalLevel {
    Low,
    Medium,
    High
}

Then apply your current converter logic to these values instead of colors, and move it to a single property in the view model:

public SignalLevel SignalLevel {
    get {
        // choose a level based on ErrorCount and HasReceivedData
    }
}

In the view model, whenever ErrorCount or HasReceivedData changes, raise NotifyPropertyChanged for SignalLevel .

In the view, do a simple translation from signal level to color:

{Binding SignalLevel, Converter={StaticResource SignalToColorConverter}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM