C# 如何访问绑定列表框中的项目,wp7
我有WP7的XAML:C# 如何访问绑定列表框中的项目,wp7,c#,xaml,windows-phone-7,C#,Xaml,Windows Phone 7,我有WP7的XAML: <ListBox x:Name="lbMain" DataContext="{Binding}" ItemsSource="{Binding Items}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock x:Name="txtNa
<ListBox x:Name="lbMain" DataContext="{Binding}" ItemsSource="{Binding Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock x:Name="txtName" Text="{Binding name}" />
<ListBox x:Name="lbCars" DataContext="{Binding}" ItemsSource="{Binding cars}" ScrollViewer.VerticalScrollBarVisibility="Disabled">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="spnlCars">
<TextBlock x:Name="txtCarName" Text="{Binding name}" />
<ListBox x:Name="lbCarColor" DataContext="{Binding}" ItemsSource="{Binding color}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock x:Name="txtColor" Text="{Binding colorValue}"/>
<Image Name="imgColor"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我的DataContex设置为我创建的ViewModel,它从webservice获取数据。数据结构为:
- 机器(有:车辆[])
- -车辆(有:名称,汽车[],卡车[],等等)--这就是我要绑定到lbMain的内容
- --汽车(有:名称、颜色[]、…)——例如,颜色[0]=“红色”
- ---色值
位图图像的程序
例如:
class ColorToImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
String colorName = (String)value;
switch (colorName.ToLower())
{
case "red":
return new BitmapImage(new Uri("..."));
default:
return new BitmapImage(new Uri("..."));
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
太棒了,谢谢你!这就是我想问的第一个问题的答案。对我的第二个问题有什么帮助吗?我在尝试访问父DataContex和尝试更改旧的ListBoxItem时遇到问题。您必须以相同的方式使用转换器,即将FontWeight绑定到颜色,然后在转换器中将颜色转换为FontWeight。我同意Francesco的观点。您只需要另一个转换器将颜色名称转换为fontwweight
类型,而不是上面示例中的BitmapImage
类型。