开发者

Binding a SelectedItem in a list box to a KeyValuePair<>

I have a list box bound to an ObservableDictionary (custom class, left out for brevity) class. And it is working great except for the binding on the SelectedItem. I have the following property bound to the selectedItem of the ListBox.

public KeyValuePair<Bumpstop, BumpStopOptions> SelectedBumpstop
    {
        get
        {
            return this.selectedBumpstop;
        }
        set
        {
            this.selectedBumpstop = value;
            this.OnPropertyChanged("SelectedBumpstop");
        }
    }

When I select an item in my list box it hits the set property and it works. When I unselect everything the ListBox gets the RedBorder around it indicating a 开发者_JAVA百科binding failure and it does not set the SelectedBumpstop property to null like I would expect. Why does it not set it to null?


Red border is not a binding failure (in the sense of binding errors found in the VS Output box), it is a validation failure.

The bindings automatically check if the new value is acceptable for the binding source type (in this case the KeyValuePair). No value selected would mean null as selected value, which is not valid for KeyValuePair - it is a structure, which are value types, therefore can't posess a null value. So the validation fails and the value is not uploaded to the source.

Making the type nullable (KeyValuePair<Bumpstop, BumpStopOptions>?) will fix this, but it can have ramifications for your other code, so think this through carefully (you may have to add nullity checks wherever the property is used).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜