绑定动态资源

3
我正在尝试使用MultiBinding作为ListBox的ItemsSource,并且我想将几个集合绑定到MultiBinding。这些集合在宿主控件(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>

我知道在绑定中无法使用DynamicResource,那我该怎么办呢?
1个回答

4
听起来你真正需要的是一个CompositeCollection,并为你的页面设置一个DataContext。 CompositeCollection 是一种将多个集合组合在一起的集合类,可以用于数据绑定。
<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。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接