我想绑定组合框的选择更改以更新我的列表框,但我的xaml代码可能是错误的。
这是我的收集来自服务的数据。
public class WorkersCollection
{
private WorkerClient client = new WorkerClient();
public ObservableCollection<Worker> Workers { get; set; }
public WorkersCollection()
{
Workers = new ObservableCollection<Worker>();
}
public ICollection<Worker> GetAllWorkers()
{
foreach (var worker in client.GetAllWorkers())
{
Workers.Add(worker);
}
return Workers;
}
}
我的DataContext是工人:
public partial class MainWindow : Window
{
WorkersCollection workers;
public MainWindow()
{
InitializeComponent();
workers = new WorkersCollection();
this.DataContext = workers;
workers.GetAllWorkers();
}
}
并在XAML中:
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem Content="{Binding LastName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}" ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem}" />
我该如何解决?
答案 0 :(得分:1)
ItemsSource
的 ListBox
属性类型为IEnumerable
(msdn)。
因此您无法为其指定Worker
类型的对象。
您可以创建转换器来执行此操作。
转换器类:
public class WorkerToListConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return new List<Worker> { value as Worker };
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
XAML代码:
...
<Window.Resources>
<local:WorkerToListConverter x:Key="myCon" />
</Window.Resources>
...
<ComboBox Name="cbxWorkers" HorizontalContentAlignment="Right" ItemsSource="{Binding Workers}">
<ComboBox.ItemTemplate>
<DataTemplate>
<ComboBoxItem Content="{Binding LastName}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<ListBox Grid.Row="3" ItemTemplate="{StaticResource WorkersTemplate}"
ItemsSource="{Binding ElementName=cbxWorkers, Path=SelectedItem, Converter={StaticResource myCon}}" />
...
您还应该从ComboBox中删除SelectedItem
绑定。
... SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}" ...
将SelectedItem
绑定到与ItemsSource
相同的内容是没有意义的。