将ListBox绑定到XAML中的SelectionChanged ComboBox

时间:2013-08-17 14:42:14

标签: wpf xaml

我想绑定组合框的选择更改以更新我的列表框,但我的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}" />

我该如何解决?

1 个答案:

答案 0 :(得分:1)

ItemsSource

ListBox属性类型为IEnumerablemsdn)。

因此您无法为其指定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相同的内容是没有意义的。