c# - WPF:聚合 ListBox 上的属性

标签 c# wpf binding listbox itemscontrol

我有两个列表框,都使用扩展选择模式。第一个的 ItemsSource 是一个列表,并使用数据模板。我正在尝试使用第一个属性的聚合作为第二个属性的 itemssource。例如:

public class MultiAppPropertyAggregator : IValueConverter {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
    IList<SomeObject> selectedItems = value as IList<SomeObject>;
    Dictionary<string, string> bundles = new Dictionary<string,string>();
    foreach(SomeObject myobj in selectedItems) {
        foreach(KeyValuePair<string,string> name in myobj.Names) {
           selectedItems.Add(name.Key, name.Value);
....

<ListBox x:Name="lstApplication" ItemsSource="{Binding}" SelectionChanged="lstApplication_SelectionChanged" SelectionMode="Extended" />
<ListBox x:Name="lstBundles" ItemsSource="{Binding ElementName=lstApplication,Path=SelectedItems,Mode=OneWay,Converter={StaticResource MultiAppPropertyAggregator}}" ItemTemplate="{StaticResource DictionaryList}" SelectedValuePath="Key" SelectionMode="Extended" />

所以第一个列表中的对象包含一个 Dictionary 类型的属性。我想将第一个列表中所有选中项的字典中的所有项添加到第二个列表中。

转换器似乎在初始加载时被调用,之后就不再调用了,最后我得到一个空的第二个列表框。我错过了什么吗?

最佳答案

我猜你的转换器只被调用一次,因为列表框中的 SelectedItems 不是 DependencyProperty,因此不会通知绑定(bind)它已更新。

您最好在您的代码隐藏/ View 模型中执行此转换(取决于您遵循的方法)并公开第二个列表框要绑定(bind)的属性。

您可以使用我能想到的两种方式之一来完成此操作。首先,您可以在第一个列表上监听 SelectionChanged 并更新第二个列表绑定(bind)到的属性。或者,您可以将 IsSelected 属性放在第一个列表绑定(bind)到的项目上,并在任何给定项目发生变化时更新您的第二个列表。您可以为 ListBoxItem 添加此样式以在数据项和 View 之间同步 IsSelected 属性:

<Style TargetType="{x:Type ListBoxItem}">
   <Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>

我的猜测是,第一个实现起来会更容易,尽管它可能无法完全符合您所遵循的任何 UI 方法。

关于c# - WPF:聚合 ListBox 上的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/666204/

相关文章:

c# - C# 中修饰符 static 对于此项错误无效

c# - 通过 C# 使用 OAuth2 RESTful 服务时授权错误 500

c# - ReSharper - var hint only for none basic type

c# - 使用其 x :Name as a parameter in a method in the code-behind 绑定(bind)按钮 IsEnabled/Visibility 属性

javascript - 如何从 Ember.js 中另一个 ArrayController 的选定值更新一个 ArrayController 的内容

c# - 如何使用 C# 运行 SQL 事务(使用 TSql110Parser)

wpf - 如何根据wpf中其他控件的属性设置控件的属性

winforms - 将具有主/详细信息的类绑定(bind)到两个 datagridview 中

wpf - 如何在 Datagrid 上绑定(bind) ObservableCollection<T>?

c# - Window.Show() 不显示窗口