【问题标题】:How to switch between 2 data sources for ListBox.ItemsSource如何在 ListBox.ItemsSource 的 2 个数据源之间切换
【发布时间】:2013-05-08 14:23:00
【问题描述】:

在给定属性上最好将 ItemsControl.ItemsSource 绑定到 2 个不同来源的最佳/优雅方法是什么?

应仅对 2 个集合之一进行绑定,ItemsControl 绑定到的集合的选择应基于某些属性。

我有一个绑定到 ViewModel 的 View。 我要绑定的集合位于该 ViewModel 下的不同层次结构路径中。

我有一个基于 MultiBinding 的解决方案,但我认为应该有更优雅的解决方案。

<CollectionViewSource x:Key="CVS">
      <CollectionViewSource.Source  >
          <MultiBinding Converter="{StaticResource myMultiBindingConverter}">
              <Binding  Path="XXXX.YYYY.ObservableCollection1"  />
              <Binding Path="XXXX.ObservableCollection2" />                    
          </MultiBinding>
      </CollectionViewSource.Source>                            
</CollectionViewSource>

<ListBox  x:Name="myListBox"                                   
          ItemsSource="{Binding Source={StaticResource CVS}}" />

转换器:

public class myMultiBindingConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
    {

        foreach (var item in values)
        {
            if(myDependecyProperty == getFirstCollection)
            {
              //make sure the item is of first collection type based on its item property
              return item;
             }
            else
            {
              //make sure the item is of the second collection type
              return item;
            }

        }
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter,
        System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

【问题讨论】:

  • 为什么不让ViewModel 包含一个组合两个集合的属性?毕竟,它应该对视图进行建模:)
  • @Rachel 我只想绑定到这两个集合中的一个,条件是我希望能够选择它是哪个集合
  • 在这种情况下,DataTrigger 在这里可能更合适,因为它会在您的条件发生变化时正确地重新评估 ItemsSource 属性。
  • @Rachel DataTrigger 是添加它作为答案的正确方法,我会接受它
  • 当然,它已被添加为答案:)

标签: wpf binding itemscontrol multibinding


【解决方案1】:

DataTrigger 在这里可能更合适,因为您想根据另一个值更改 ItemsSource 绑定

<Style x:Key="MyListBoxStyle" TargetType="ListBox">
    <Setter Property="ItemsSource" Value="{Binding XXX.ObservableCollection2}" />
    <Style.Triggers>
        <DataTrigger Binding="{Binding SomeValue}" Value="SecondCollection">
            <Setter Property="ItemsSource" Value="{Binding XXX.YYY.ObservableCollection2}" />
        </DataTrigger>
    </Style.Triggers>
</Style>

与转换器不同,DataTrigger 将在触发值更改时正确地重新评估

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2016-03-04
    • 2011-06-22
    • 1970-01-01
    • 2019-02-25
    • 2018-07-18
    相关资源
    最近更新 更多