【问题标题】:How to use a property of the view model in a CompositeCollection?如何在 CompositeCollection 中使用视图模型的属性?
【发布时间】:2016-05-24 15:07:39
【问题描述】:

当我的视图中有一个组合框并且希望一个空项目能够取消选择该选项时,我在我的视图中使用此代码:

<ComboBox.Resources>
    <CollectionViewSource x:Key="comboBoxSource" Source="{Binding ElementName=ucPrincipal, Path=DataContext.MyProperty}" />
</ComboBox.Resources>
<ComboBox.ItemsSource>
    <CompositeCollection>
        <entities:MyType ID="-1"/>
        <CollectionContainer Collection="{Binding Source={StaticResource comboBoxSource}}" />
    </CompositeCollection>
</ComboBox.ItemsSource>

在这种情况下,是视图将 ID 设置为 -1 以指示这是特殊项目。但我不太喜欢这种解决方案,因为视图模型取决于视图是否正确设置。

所以我想在我的视图模型中有这个属性:

public readonly MyType MyNullItem = new MyType();

但我不知道如何在视图中的复合集合中使用它,而不是:

<entities:MyType ID="-1"/>

有可能吗?

谢谢。

【问题讨论】:

    标签: wpf data-binding wpf-controls compositecollection


    【解决方案1】:

    您需要某种绑定转换器,它将一个列表和一个对象组合成CompositeCollection。前段时间我实现了类似的转换器,唯一的区别是将多个集合转换为一个:

    /// <summary>
    /// Combines multiple collections into one CompositeCollection. This can be useful when binding to multiple item sources is needed.
    /// </summary>
    internal class MultiItemSourcesConverter : IMultiValueConverter {
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) {
            var result = new CompositeCollection();
    
            foreach (var collection in values.OfType<IEnumerable<dynamic>>()) {
                result.Add(new CollectionContainer { Collection = collection });
            }
            return result;
        }
    
        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) {
            throw new NotSupportedException();
        }
    }
    

    这种转换器在 XAML 中的用法如下所示:

    <ComboBox.ItemsSource>
        <MultiBinding Converter="{StaticResource MultiItemSourcesConverter}">
            <Binding Path="FirstCollection" />
            <Binding Path="SecondCollection" />
        </MultiBinding>
    </ComboBox.ItemsSource>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 2018-06-15
      • 2023-03-31
      相关资源
      最近更新 更多