• WPF中ComboBox控件的SelectedItem和SelectedValue的MVVM绑定


    问题描述:左侧是一个ListView控件,用于显示User类的Name属性,右侧显示其SelectedItem的其他属性,包括Age, Address,和Category。其中Category用ComboBox表示。在下拉框选中其他category,可以更改User的属性值。

     

     

     如果Category是string类型,即User类的定义如下

    public class User
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string category { get; set; }
            public string Address { get; set; }
        }
    User Class

    那么,combobox的绑定代码如下:

    <ComboBox Width="150" Canvas.Left="80" ItemsSource="{Binding Path=Categories}" 
                              SelectedItem="{Binding ElementName=listview, Path=SelectedItem.category, Mode=TwoWay}" Name="cbotypes"/>

    直接绑定到了SelectedItem属性。

    如果Category是个复合类型,即User类和Category类定义如下:

    public class User
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public  Category category { get; set; }
            public string Address { get; set; }
        }
    
        public class Category
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    Category&User class

    那么,combobox的绑定代码如下:

    <ComboBox Width="150" Canvas.Left="80" ItemsSource="{Binding Path=Categories}" DisplayMemberPath="Name"
                              SelectedItem="{Binding ElementName=listview, Path=SelectedItem.category, Mode=TwoWay}" SelectedValuePath="Name" 
                              SelectedValue="{Binding ElementName=listview, Path=SelectedItem.category.Name}" Name="cbotypes"/>

    使用DisplayMemberPath指定了绑定到Category类中的Name属性,并使用了SelectedValue和SelectedValuePath绑定到具体的SelctedItem.

    全部源代码:

    https://github.com/Larissa1990/WPF_ComboBox_SelectedItem

  • 相关阅读:
    java中 Hex(十六进制)和byte[]相互转换
    byte[]和File相互转换
    Stringboot MultiPartFile 转 File
    mysql8.0+运行报错The server time zone value 'Öйú±ê׼ʱ¼ä' is unrecognized or represents more than one time zone. 解决办法
    idea激活
    mysql8安装成功过后navicat连接失败
    AJAX的使用
    单文件上传和多文件上传实例
    监听器的使用
    SQL分页技术
  • 原文地址:https://www.cnblogs.com/larissa-0464/p/13190446.html
Copyright © 2020-2023  润新知