【问题标题】:Bind combobox items source to certain property of those objects将组合框项目源绑定到这些对象的某些属性
【发布时间】:2026-02-22 06:15:01
【问题描述】:

假设我有一个包含 name 和 id 属性的 TeamParameter 对象列表。我想要一个组合框,它将显示 TeamParameter 对象的列表,但只向用户显示组合框中每个对象的名称属性。有没有办法在 MainWindow.xaml 中绑定到该属性?

尝试点表示法认为它可以工作,但没有。

MainViewModel.cs

public class MainViewModel : ViewModelBase
{
        private List<TeamParameters> _teams;

        public class TeamParameters
        {
            public string Name { get; set; }

            public int Id { get; set; }
        }

        public List<TeamParameters> Teams
        {
            get { return _teams; }
            set { Set(ref _teams, value); }
        }
}

MainWindow.xaml

<Window x:Class="LiveGameApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:LiveGameApp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800"
        DataContext="{Binding Main, Source={StaticResource Locator}}">



    <DockPanel>
        <ComboBox  Name="TeamChoices" ItemsSource="{Binding Team.Name}"  DockPanel.Dock="Top" Height="30" Width="175" VerticalContentAlignment="Center" HorizontalContentAlignment="Center"></ComboBox>
    </DockPanel>
</Window>

【问题讨论】:

  • 将您的 ItemSource 绑定更改为 ItemsSource="{Binding Teams}" 并提供 ComboBox 的 DisplayMemberPath 属性作为名称,如 DisplayMemvberPath="Name"
  • 谢谢,现在一切都好!

标签: c# wpf mvvm mvvm-light


【解决方案1】:

要指向数据模型上的特定属性,您可以通过设置 DisplayMemberPath 来指定成员路径:

<ComboBox  ItemsSource="{Binding Teams}" DisplayMemberPath="Name" />

当您没有提供DataTemplate 并且没有为ItemsControl 的项目指定DisplayMemberPath 时,控件将默认显示项目的string 表示。这是通过在每个项目上调用 Object.ToString() 来完成的。因此,作为替代方案,您始终可以覆盖 TeamParameters 类型的 Object.ToString()(或一般的项目模型):

public class TeamParameters
{
  public override string ToString() => this.Name;

  public string Name { get; set; }

  public int Id { get; set; }
}

XAML

<ComboBox  ItemsSource="{Binding Teams}" />

或者简单地提供一个DataTemplate

<ComboBox ItemsSource="{Binding Teams}">
    <ComboBox.ItemTemplate>
        <DataTemplate DataType="TeamParameters">
            <TextBlock Text="{Binding Name}" /> 
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

【讨论】:

  • 我没想过要覆盖 ToString() ,但这为我打开了一个有趣的选项。我现在选择了显示成员路径选项,一切都很好。谢谢!
最近更新 更多