ListBox SelectedItems绑定

Pol*_*ris 8 c# data-binding wpf

我想将Listbox selectedItems绑定到数组.但.NET在运行时抛出异常.

d.SetBinding(ListBox.SelectedItemsProperty, new Binding { Source = SomeArray });
Run Code Online (Sandbox Code Playgroud)

dXAML中的一些ListBox 在哪里.

例外:

所选项目无法绑定.

为什么?

Kep*_*mun 8

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

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

在Xaml中:

<StackPanel>

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

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

</StackPanel>
Run Code Online (Sandbox Code Playgroud)

在代码隐藏中:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这似乎与OneWayToSource绑定有关.如果我更改SelectedItems集合,则更改不会反映在列表框中. (2认同)
  • Downvoted是因为建议在代码隐藏中使用事件处理程序来调用视图模型不遵循MVVM模式.如果你不介意代码隐藏(我确实介意它,但无论如何),那么使用它.但是,请不要通过从代码隐藏调用它们来污染视图模型. (2认同)

Aka*_*ava 5

This is the working solution, however when selection changes SelectedItemsProperty does not refresh bindings...

您可以按如下方式创建自定义控件

public class MyListBox: ListBox{

    public MyListBox()
    { 
         this.SelectionChanged += (s,e)=>{ RefreshBindings(); };
    }

    private void RefreshBindings()
    {
         BindingExpression be = 
             (BindingExpression) GetBindingExpression(
                                      SelectedItemsProperty);
         if(be!=null){
               bd.UpdateTarget();
         }
    }

}
Run Code Online (Sandbox Code Playgroud)

或者在您的应用程序中,您可以在每个列表框中定义事件,如下所示..

myListBox.SelectionChanged += (s,e) => {
    BindingExpression be = 
         (BindingExpression) myListBox.GetBindingExpression(
                                      ListBox.SelectedItemsProperty);
    if(be!=null){
        bd.UpdateTarget();
    }
};
Run Code Online (Sandbox Code Playgroud)


wpf*_*abe 1

ListBox.SelectedItems是只读的。您的意思是绑定到ListBox.SelectedItem吗?

  • 由于该属性是只读的,因此您无法将其用于您想要的用途。我唯一能想到的就是设置单独的“ListBoxItem.IsSelected”属性。如果您坚持绑定,最简单的路径是您在属性更改事件处理程序中使用自定义逻辑创建例如附加的 SelectedItems `DependencyProperty`。 (2认同)