0

我在类后面有以下代码,

我在 xaml 中有一个 cobobox。我想将它与这个类绑定。下面的代码使组合框包含 2 项“任意”和“可配置”

但是当我运行应用程序时,组合框是空的。没有选择默认值。这个怎么做?

public class ReadData:INotifyPropertyChanged
{

    private string typeData="Arbitrary";
    private string[] typeDataList={"Arbitrary", "Configurable"};
    private ICollectionView typeDataList;

    public string[] TypeDataList
    {
        get
        {
            return typeDataList;
        }
        set
        {
            typeDataList=value;
            NotifyProertyChanged("TypeDataList");
        }
    }

public string TypeData
{
get
{
return typeData;
}
set
{
typeData=value;
NotifyPropertyChanged("TypeData");
}

public ICollectionView TypeDataListView
{
get
{
typeDataListView=CollectionViewSource.GetDefaultView(typeDataList);
return typeDataListView;
}
set
{
typeDataListView=value;
//typeDataList= ???
}
}

XAML 文件

<ComboBox ItemSource={Binding TypeDataListView}" IsSynchronizedWithCurrentItem="True" SelectedItem="{Binding typeData}" Height="23" Width="120"/>
4

1 回答 1

1

我猜您不仅想要绑定项目源,而且组合框的选择对您也很重要,因此您还想在视图模型上添加选择。有两种方法:

  1. 在 ReadData 类上添加 SelectedTypeData 属性,其类型为字符串。将 ComboBox 的 SelectedItem 绑定到 SelectedTypeData。然后在 ReadData 对象的初始化中,您可以为 SelectedTypeData 分配一个默认值作为 ComboBox 上的默认选择。

  2. 在 ReadData 类上添加 TypeDataListView 属性,其类型为 ICollectionView。它可能要求您的 TypeDataList 是一个列表。它可以通过调用 CollectionViewSource.GetDefaultView(...) 生成。您可以将其 CurrentItem 属性指定为默认选择,并将 Combobox 的 IsSynchronizedWithCurrentItem 属性指定为 true,以便您可以将组合框的选定项与 TypeDataListView 的 CurrentItem 同步。

如果您不想在视图模型上添加选择,您可以在代码后面添加一个 Loaded 事件,并在处理程序中手动分配组合框的选定项。

于 2013-07-31T17:38:06.363 回答