views:

99

answers:

4

What is the typical pattern for displaying an "unavailable" value when databinding in WPF?

For example I am using MVVM, and TextBlocks in my view are bound to my viewmodel's properties, some of which are ints. There are times when I want to temporarily display two dashes ("--") in my view rather than the property value.

I could change the property to be a string, and then in the getter add some logic to specify whether it returns the value or "--". This is probably the appropriate way to use MVVM, but are there any easier ways?

Is there a way to take advantage of a TextBlock's FallbackValue? Or is there another approach for temporarily suspending databinding and displaying a "unavailable" value?

A: 

Since a TextBlock already displays text, why not just add a custom IMultiValueConverter to the binding which returns "--" in case of, say, some bool value on the VM?

kek444
A: 

WPF already uses converters behind the scenes (such as int to string) to display your values in the text blocks. If you want to change the functionality, you can provide a simple custom converter to handle any special case you can think of.

Tim Rupe
+3  A: 

FallbackValue is only used when the binding path cannot be resolved, or the converter returns DependencyProperty.UnsetValue. Converters are generally shunned when doing MVVM. My suggestion would be to have two properties, one that contains the int value and one that contains the display value:

public int SomeValue
{
    get { return _someValue; }
    set
    {
        if (_someValue != value)
        {
            _someValue = value;
            OnPropertyChanged("SomeValue");
            OnPropertyChanged("SomeValueDisplay");
        }
    }
}

public string SomeValueDisplay
{
    get { return _someValue == -1 ? "--" : _someValue.ToString(); }
}

This gives you the best of both worlds. Your VM logic works with the int property, but your TextBlock binds directly to a string representation of the underlying int.

HTH, Kent

Kent Boogaart
`SomeValueDisplay` should be a string, not int
Thomas Levesque
Thanks for your answer. In my case I would not actually need the second property--I can just change my property to a string directly.
emddudley
@Thomas: thanks - edited.
Kent Boogaart
A: 

you could use a nullable int for the property, and in the binding specify TargetNullValue=--.

If you need the original value anyway, you could use your actual int value as backing store and use logic for determining whether to return the value or null.

Botz3000