【问题标题】:Binding a DynamicResource绑定动态资源
【发布时间】:2008-11-04 16:22:23
【问题描述】:

我正在尝试使用 MultiBinding 作为 ListBox 的 ItemsSource,并且我想将几个集合绑定到 MultiBinding。直到已经实例化宿主控件(Page 的派生)之后,才会填充集合。在构建完成之后,我调用了一个方法来设置 Page 的一些数据,包括这些集合。

现在,我有这样的事情:

public void Setup()
{
    var items = MyObject.GetWithID(backingData.ID); // executes a db query to populate collection  
    var relatedItems = OtherObject.GetWithID(backingData.ID);
}

我想在 XAML 中做这样的事情:

<Page ...

  ...

    <ListBox>
        <ListBox.ItemsSource>
            <MultiBinding Converter="{StaticResource converter}">
                <Binding Source="{somehow get items}"/>
                <Binding Source="{somehow get relatedItems}"/>
            </MultiBinding>
        </ListBox.ItemsSource>
    </ListBox>
  ...
</Page>

我知道我不能在 Binding 中使用 DynamicResource,我该怎么办?

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    在我看来,您真正想要的是 CompositeCollection 并为您的页面设置 DataContext。

    <Page x:Class="MyPage" DataContext="{Binding RelativeSource={RelativeSource Self}}">
        <Page.Resources>
            <CollectionViewSource Source="{Binding Items}" x:Key="items" />
            <CollectionViewSource Source="{Binding RelatedItems}" x:Key="relatedItems" />
        </Page.Resources>
    
        <ListBox>
           <ListBox.ItemsSource>
             <CompositeCollection>
               <CollectionContainer
                 Collection="{StaticResource items}" />
               <CollectionContainer
                 Collection="{StaticResource relatedItems}" />
             </CompositeCollection>
           </ListBox.ItemsSource>
        </ListBox>
    </Page>
    

    后面的代码如下所示:

    public class MyPage : Page
    {
        private void Setup()
        {
            Items = ...;
            RelatedItems = ...;
        }
    
        public static readonly DependencyProperty ItemsProperty =
            DependencyProperty.Register("Items", typeof(ReadOnlyCollection<data>), typeof(MyPage),new PropertyMetadata(false));
        public ReadOnlyCollection<data> Items
        {
            get { return (ReadOnlyCollection<data>)this.GetValue(ItemsProperty ); }
            set { this.SetValue(ItemsProperty , value); } 
        }
    
        public static readonly DependencyProperty RelatedItemsProperty =
            DependencyProperty.Register("RelatedItems", typeof(ReadOnlyCollection<data>), typeof(MyPage),new PropertyMetadata(false));
        public ReadOnlyCollection<data> RelatedItems
        {
            get { return (ReadOnlyCollection<data>)this.GetValue(RelatedItemsProperty ); }
            set { this.SetValue(RelatedItemsProperty , value); } 
        }
    }
    

    编辑:我记得 CollectionContainer 不参与逻辑树,因此您需要使用 CollectionViewSource 和 StaticResource。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 2011-04-05
      • 2020-01-17
      • 2015-01-20
      • 2011-09-12
      • 1970-01-01
      • 2017-06-15
      相关资源
      最近更新 更多