使用带有ComboBox.SelectedValue的MultiConverter:" ConvertBack"的值永远是空的

时间:2017-01-12 15:10:54

标签: c# wpf xaml

我有以下情况:在我的视图模型中,我有两个属性,让它们为CreateNewThingSelectedExistingThingCreateNewThing的类型为boolSelectedExistingThing的类型为Thing

我现在有一个显示两个静态条目的ComboBox,"无"和"创建新的",以及Thing的列表。我把它连接起来:

事物清单的集合:

       <ComboBox.Resources>
            <CollectionViewSource x:Key="AllThings" Source="{Binding ViewModel.AllThings, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControl}}}" />
            <tools:ThingSelector x:Key="ThingSelector" />
        </ComboBox.Resources>

ItemsSource的设置:

        <ComboBox.ItemsSource>
            <CompositeCollection>
                <tools:PlaceholderForNone />
                <tools:PlaceholderForNew />
                <Separator />
                <CollectionContainer Collection="{Binding Mode=OneWay, Source={StaticResource AllThings}}" />
            </CompositeCollection>
        </ComboBox.ItemsSource>

绑定SelectedValue

        <ComboBox.SelectedValue>
            <MultiBinding Converter="{StaticResource ThingSelector}">
                <Binding Path="ViewModel.CreateNewThing" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControl}}" />
                <Binding Path="ViewModel.SelectedExistingThing" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type local:MyCustomControl}}" />
            </MultiBinding>
        </ComboBox.SelectedValue>

我的ThingSelector看起来像这样:

internal sealed class ThingSelector: IMultiValueConverter {

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
        if((values == null) ||
           (values.Length != 2) ||
           (!(values[0] is bool))) {
            return Binding.DoNothing;
        }
        if((bool)values[0]) {
            return new PlaceholderForNew();
        }
        if(values[1] is Thing) {
            return values[1];
        }
        return new PlaceholderForNone();
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
        if(value is PlaceholderForNew) {
            return new object[] { true, null };
        }
        return new object[] { false, value as Thing};
    }
}

对于所有相同类型的对象,PlaceholderForXXX的{​​{1}}始终为0而HashCodeEquals,所以这两个{{1}是等于。

现在奇怪的是:我可以选择&#34;无&#34;和#34;创建新的&#34;我的组合框中的选项,并且它们被正确传播(即,选择&#34; new&#34;选项将true属性设置为PlaceholderForXXX,将CreateNewThing属性设置为{{ 1}})。 但是,当我从组合框中选择true时,调用SelectedExistingThing方法,参数nullThing,根据我的理解,它应该是选中的显然不是ConvertBack的{​​{1}}的值(如果我将相应的事件放入代码隐藏中,我真的看到valuenull而不是null

我错过了什么?

0 个答案:

没有答案