【问题标题】:How to show default value in a combobox using binding?如何使用绑定在组合框中显示默认值?
【发布时间】:2013-08-01 11:23:56
【问题描述】:

我在类后面有以下代码,

我在 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"/>

【问题讨论】:

    标签: wpf xaml data-binding mvvm


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 你的意思是我必须将我的 string[] 转换为 ICollectionView?没有ICollectionView,是不是不行呢?我正在使用 .NET 4。我没有 CollectionViewSource 类。
    • .Net 4 内置了 CollectionViewSource。你可以保留你的 string[] 但你需要添加一个属性来绑定 ListBox 的 SelectedItem。请参阅我的第一点。
    • 对不起,是的。 .NET 4 有 CollectionViewSource 类。我根据你的帖子更新了。但是,仍然不显示默认选择的项目。我在这里错过了什么吗?
    猜你喜欢
    • 2011-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    相关资源
    最近更新 更多