WPF获取组合框选择文本(MVVM)

时间:2014-05-03 10:55:56

标签: c# wpf xaml mvvm combobox

我有一个ComboBox,我想将选定的项目文本绑定到视图模型中的字符串。

现在我有:

的Xaml:

<ComboBox DataContext="{Binding AllDataTypes}" SelectedItem="{Binding Type}" />

视图模型:

private String type;

public String Type
{
    get
    {
        return type;
    }
    set
    {
        if (type == value)
        {
            return;
        }

        type = value;
        RaisePropertyChanged(() => Type);
    }
}

当我运行该程序时,我得到了一个例外:

  

BindingExpression路径错误:&#39;键入&#39;在&#39; object&#39;上找不到的属性&#39;&#39; ObservableCollection`1&#39; (的HashCode = 34166919)&#39 ;. BindingExpression:路径=类型;的DataItem =&#39; ObservableCollection`1&#39; (的HashCode = 34166919);目标元素是&#39; ComboBox&#39; (名称=&#39;&#39); target属性是&#39; SelectedItem&#39; (键入&#39;对象&#39;)

1 个答案:

答案 0 :(得分:3)

DataContext更改为ItemsSource

<ComboBox ItemsSource="{Binding AllDataTypes}" SelectedItem="{Binding Type}" />
相关问题