c# - 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 字典中获取其值范围?
解决方案
如果您的汽车颜色属性是 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)},
推荐阅读
- c - c 中的文件 i/o 和缓冲区操作
- c++ - 如果读取文件时间超过 5 分钟,则停止 (C++ std::ifstream)
- django - 在 Django ModelForm 中使用 Postgres 默认值
- c# - 使用 App.Config 在 MVC 中共享库
- pyspark - Glue AWS:调用 o60.getDynamicFrame 时发生错误
- java - 在 JWT/JSON 中添加字节数组
- javascript - IMG 元素内的 SVG(作为数据 URL)与 DIV 内的 SVG - 性能差异
- mysql - MySQL 中的排除
- c++ - 游戏功能和阻塞接受,socket c++
- c# - 如何在数据库 C# 的数据网格视图中显示 Double 类型的数据?