绑定DynamicResource

时间:2008-11-04 16:22:23

标签: c# wpf data-binding

我正在尝试使用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>

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

1 个答案:

答案 0 :(得分:4)

听起来像你真正想要的是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。