【问题标题】:How to fil a ComboBox with MVVM Light binding and XAML?如何使用 MVVM Light 绑定和 XAML 填充 ComboBox?
【发布时间】:2015-10-20 12:29:03
【问题描述】:

我有一个列表,其中包含我想在 ComboBox 中显示的项目,但结果是我没有看到文本,但是:

 App1.Data.Models.Test
 App1.Data.Models.Test
 App1.Data.Models.Test

我真的不知道如何显示正确的文本。

模型 Test 有 2 个属性 ID 和 Name。

 <ComboBox Grid.Column="1"
           Grid.Row="3"
           Margin="10"
           ItemsSource="{Binding TestList}" />

我需要像 ListView 一样使用 DataTemplate 吗?

【问题讨论】:

    标签: c# xaml binding combobox mvvm-light


    【解决方案1】:

    ComboBox 使用其项目的ToString() 方法来显示它们。

    要么覆盖App1.Data.Models.Test.ToString(),要么选择App1.Data.Models.Test的特定属性来显示,比如说Name

    <ComboBox
           Grid.Column="1"
           Grid.Row="3"
           Margin="10"
           ItemsSource="{Binding TestList}"
           DisplayMemberPath="Name" />
    

    【讨论】:

    • 它说属性“路径”设置不止一次。
    【解决方案2】:

    您需要从App1.Data.Models.Test 定义您要通过DisplayMemberPath 显示的属性。 或者覆盖ToString()

    <ComboBox Grid.Column="1"
           Grid.Row="3"
           Margin="10"
           DisplayMemberPath = "Name"
           ItemsSource="{Binding TestList}" />
    

    【讨论】:

    • 啊,确实!并且使用 SelectedItem 可以将整个对象取回? ID 和姓名?
    • 是的。将其绑定到 App1.Data.Models.Test 类型的属性
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-06
    • 2013-11-07
    • 1970-01-01
    • 2017-02-08
    • 2011-03-10
    • 1970-01-01
    相关资源
    最近更新 更多