首页 > 解决方案 > 如何从对象发送到组合框 1 属性

问题描述

我写了这个组合框

<ComboBox 
    x:Name="ComboBoxRole" 
    SelectedItem="{Binding ApplicationModel.CategoryName}"  
    ItemsSource="{Binding Categories}"  
    Style="{StaticResource ComboBoxStyle}" Text="Choose"
    />

对于这个模型

public class CategotyModel : INotifyPropertyChanged, IDataErrorInfo
{
    private string id;
    private string name;

    public string Id
    {
        get => id;
        private set
        {
            id = value;
            NotifyPropertyChanged("Id");
        }
    }
    public string Name
    {
        get => name;
        private set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }
 }

为项目来源创建此属性

public IList<CategotyModel> Categories
    {
        get
        {
            var categoriesDTO = _categoryManager.GetAllCategories();
            this.categories = mapper.DefaultContext.Mapper.Map<IList<CategotyModel>>(categoriesDTO);
            return categories;
        }
    }

它工作起来很有趣,但我不知道如何仅将 1 个参数发送到组合,因为我接受"AppStore.WPF.MVVMLight.Models.CategotyModel"对象。

注意:我从服务器获取结果。没关系。

(没有 foreachIList<CategoryModel>并写入字符串列表 - 我认为这是不好的方式)。

编辑

<ComboBox 
    x:Name="ComboBoxRole" 
    SelectedItem="{Binding ApplicationModel.CategoryName}" 
    SelectedValuePath="Name" 
    DisplayMemberPath="Name" 
    ItemsSource="{Binding Categories}"  
    Style="{StaticResource ComboBoxStyle}" 
    Text="Choose"
    />

标签: c#wpfmvvm

解决方案


您需要修复 ComboBox 中的一些问题: 要显示项目的 Name 属性,请添加DisplayMemberPath="Name". 要仅选择所选项目的名称属性而不是整个对象,请添加SelectedValuePath="Name"并绑定ApplicationModel.CategoryNameSelectedValue而不是SelectedItem. SelectedItem即使SelectedValuePath在使用中,它仍然是整个对象。

<ComboBox 
    x:Name="ComboBoxRole" 
    SelectedValue="{Binding ApplicationModel.CategoryName}" 
    SelectedValuePath="Name" 
    DisplayMemberPath="Name" 
    ItemsSource="{Binding Categories}"  
    Style="{StaticResource ComboBoxStyle}" 
    Text="Choose"
    />

推荐阅读