0

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

我该如何解决?

4

1 回答 1

1

ItemsSource类的属性ListBox具有类型IEnumerable( msdn )。

所以你不能给它分配 type 的对象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}}" />
...

您还应该SelectedItem从 ComboBox 中删除绑定。

   ... SelectedItem="{Binding Workers}" ItemsSource="{Binding Workers}" ...

绑定SelectedItem到与ItemsSource.

于 2013-08-17T15:09:39.890 回答