首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绑定DynamicResource

绑定DynamicResource
EN

Stack Overflow用户
提问于 2008-11-04 16:22:23
回答 1查看 7K关注 0票数 3

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

现在,我有这样的东西:

代码语言:javascript
复制
public void Setup()
{
    var items = MyObject.GetWithID(backingData.ID); // executes a db query to populate collection  
    var relatedItems = OtherObject.GetWithID(backingData.ID);
}

我想在XAML中做一些类似的事情:

代码语言:javascript
复制
<Page ...

  ...

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

我知道我不能在绑定中使用DynamicResource,那我该怎么办呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2008-11-04 16:31:42

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

代码语言:javascript
复制
<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>

后面的代码看起来像这样:

代码语言:javascript
复制
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。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/262343

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档