【发布时间】:2018-12-10 09:25:05
【问题描述】:
我是 WPF 领域的新手,有以下关于数据绑定的问题。
我的测试应用包含一个带有汽车的 ListView(列:类型、速度和颜色)。在列表视图下方,有一些控件可以控制所选汽车的值。其中有一个 ComboBox 可以选择所选汽车的颜色。
在 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