首页 > 解决方案 > WPF:如何将 ComboBox 数据绑定到 ListView 选择并设置 ComboBox 值范围?

问题描述

我是 WPF 领域的新手,并且有以下关于数据绑定的问题。

我的测试应用程序包含一个带有汽车的 ListView(列:类型、速度和颜色)。在列表视图下方,有一些控件可以控制所选汽车的值。除其他外,还有一个组合框可以选择所选汽车的颜色。

我的测试应用看起来像这样

在 XAML 中,ListView 的初始化如下:

    <ListView Grid.Row="1" Name="listView"  ItemsSource="{Binding Model.Cars}" SelectedValue="{Binding Model.SelectedCar}">
  <ListView.View>
    <GridView>
      <GridView.Columns>
        <GridViewColumn Header="Type" Width="Auto" DisplayMemberBinding="{Binding Name}" />
        <GridViewColumn Header="Speed" Width="Auto" DisplayMemberBinding="{Binding Speed}" />
        <GridViewColumn Header="Color" Width="Auto"
                        DisplayMemberBinding="{Binding Color.Value}"/>
      </GridView.Columns>
    </GridView>
  </ListView.View>
</ListView>

ItemsSource 是 Model.Cars,它是 Car 对象的 ObservableCollection。Car.Color 是由 CarColors 类的 AvailableColors 初始化的 KeyValuePair (Color, string):

  public static class CarColors
  {
    static Random rnd = new Random();

    private static Dictionary<Color, string> availableColors = new Dictionary<Color, string>
    {
      { Colors.Red,  "red" },
      { Colors.Green,  "green" },
      { Colors.Blue,  "blue" },
      { Colors.Yellow,  "yellow" },
      { Colors.Brown,  "brown" },
      { Colors.Silver,  "silver" },
    };

    public static Dictionary<Color, string> GetAvailableColors()
    {
      return availableColors;
    }

    public static KeyValuePair<Color, string> GetRandomColor()
    {
      return availableColors.ElementAt(rnd.Next(0, availableColors.Count));
    }
  }

我想将 Color ComboBox 与 ListView 中所选汽车的颜色进行数据绑定。我当前的 XAML 代码不起作用:

      <ComboBox Grid.Row="1" Grid.Column="1" Margin="2"
            ItemsSource="{Binding Source={StaticResource AvailableColors}}"
            SelectedValuePath="Key"
            DisplayMemberPath="Value"
            SelectedValue="{Binding ElementName=listView, Path=SelectedValue}"/>

如何对 Color ComboBox 进行数据绑定,使其代表所选汽车的颜色,但从静态 CarColors 字典中获取其值范围?

标签: c#wpflistviewcomboboxrange

解决方案


如果您的汽车颜色属性是 KeyValuePair,请尝试以下操作:

<ComboBox Grid.Row="1" Grid.Column="1" Margin="2"
        ItemsSource="{Binding AvailableColors}"
        SelectedItem="{Binding ElementName=listView, Path=SelectedItem.Color}"
        DisplayMemberPath="Value"/>

注意。任何汽车对象的颜色属性必须指向 AvailableColors 源颜色列表的一个元素。IE。

 new Car { Name = "Ford", Speed = 180f, Color = AvailableColors.ElementAt(1)},

推荐阅读