【问题标题】:WPF: How to data bind a ComboBox to ListView selection and set the ComboBox value range?WPF:如何将 ComboBox 数据绑定到 ListView 选择并设置 ComboBox 值范围?
【发布时间】:2018-12-10 09:25:05
【问题描述】:

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

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

My test app looks like this

在 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 是一个 KeyValuePair (Color, string),由 CarColors 类的 AvailableColors 初始化:

  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 字典中获取其值范围?

【问题讨论】:

  • 您应该将组合的 selectedvalue 绑定到“SelectedValue.Color”,因为 ListView SelectedValue 是汽车,而不是颜色。

标签: c# wpf listview combobox range


【解决方案1】:

如果你的汽车颜色属性是 KeyValuePair,试试这个:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-28
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多