Kristoffer Fast
Kristoffer Fast

Reputation: 145

x:Bind in resource dictionary doesn't work

I'm struggling to get a grip of the compiled databinding concept. I have one view (MainPage) that contains a ListBox and one data template (ItemTemplate) used for that ListBox. The MainPage has a MainPageViewModel that contains an ObservableCollection of ItemViewModels. The ItemViewModel contains only one property Name.

MainPage:

<Page x:Class="TestApp.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestApp">
    <Page.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ItemDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Page.Resources>

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <ListBox ItemsSource="{x:Bind ViewModel.Items}"
                 ItemTemplate="{StaticResource ItemTemplate}" />
    </Grid>
</Page>

Resource dictionary containing datatemplate:

<ResourceDictionary
    x:Class="TestApp.ItemDictionary"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:TestApp">

    <DataTemplate x:Key="ItemTemplate" x:DataType="local:ItemViewModel">
        <TextBlock Text="{x:Bind Name}" />
    </DataTemplate>    
</ResourceDictionary>

This code compiles but when I run it the binding to the Name property fails, although the items get generated. If I use a classic binding everything works fine and if I place the data template directly in the resources for the MainPage it also works. What am I missing?

Upvotes: 2

Views: 893

Answers (1)

Kristoffer Fast
Kristoffer Fast

Reputation: 145

Correct:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <local:ItemDictionary />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

Incorrect:

<Page.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="ItemDictionary.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Page.Resources>

Upvotes: 5

Related Questions