将组合框项目源绑定到那些对象的某些属性

时间:2019-10-31 01:49:50

标签: c# wpf mvvm mvvm-light

说我有一个具有name和id属性的TeamParameter对象的列表。我想要一个组合框,该组合框将显示TeamParameter对象的列表,但仅向用户显示组合框中的每个nameName属性。是否可以在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>

1 个答案:

答案 0 :(得分:1)

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

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

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

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>