ListBox SelectedItems绑定 [英] ListBox SelectedItems Binding

查看:288
本文介绍了ListBox SelectedItems绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将列表框selectedItems绑定到数组。但是.NET在运行时会引发异常。

I want to bind Listbox selectedItems to array. But .NET throws exception at runtime.

d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray });

其中 d 是XAML的一些ListBox。

Where d is some ListBox from XAML.

例外:


所选项目无法绑定。

Selected Item cannot be bound.

为什么?

推荐答案

您可以订阅ListBox的SelectionChanged事件,并在处理程序中同步所选项目的集合。

You can subscribe to the SelectionChanged event of the ListBox, and in the handler sync a collection of selected items.

在此示例中,Windows DataContext在其构造函数中设置为其自身(此)。您还可以从事件处理程序中轻松调用逻辑层(如果使用MVVM,则可以调用ViewModel)。

In this example the Windows DataContext was set to itself (this) in its constructor. You could also easily call into a logic layer (ViewModel if you're using MVVM) from the event handler.

在Xaml中:

<StackPanel>

    <ListBox
        ItemsSource="{Binding ListBoxItems}"
        SelectionMode="Multiple"
        SelectionChanged="ListBox_SelectionChanged">
    </ListBox>

    <ItemsControl
        ItemsSource="{Binding SelectedItems}">
    </ItemsControl>

</StackPanel>

在后面的代码中:

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (string item in e.RemovedItems)
    {
        SelectedItems.Remove(item);
    }

    foreach (string item in e.AddedItems)
    {
        SelectedItems.Add(item);
    }
}

这篇关于ListBox SelectedItems绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆