Dynamic Source Linking

I am trying to use MultiBinding as an ItemsSource for a ListBox, and I want to associate a couple of collections with a MultiBinding. Collections are not populated until an instance of host management is created (page output). After creating, I call a method that sets some data for the page, including these collections.

I now have something like this:

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

and I want to do something like this in XAML:

<Page ...

  ...

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

I know I cannot use DynamicResource in Binding, so what can I do?

+3
source share
1 answer

It seems to me that you really want a CompositeCollection and set up a DataContext for your page.

<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>

The code behind would look something like this:

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

Source: https://habr.com/ru/post/1699116/


All Articles