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 在哪里.
例外:
所选项目无法绑定.
为什么?
您可以订阅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)
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)
ListBox.SelectedItems是只读的。您的意思是绑定到ListBox.SelectedItem吗?
| 归档时间: |
|
| 查看次数: |
18577 次 |
| 最近记录: |