xaml - x :Bind in resource dictionary doesn't work

标签 xaml mvvm uwp xbind compiled-bindings

我正在努力掌握已编译的数据绑定(bind)概念。我有一个 View (MainPage),其中包含一个列表框和一个用于该列表框的数据模板(ItemTemplate)。 MainPage 有一个 MainPageViewModel,其中包含 ItemViewModel 的 ObservableCollection。 ItemViewModel 仅包含一个属性名称。

主页:

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

包含数据模板的资源字典:

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

此代码可以编译,但当我运行它时,尽管生成了项目,但与 Name 属性的绑定(bind)失败。如果我使用经典绑定(bind),一切都会正常工作,如果我将数据模板直接放置在主页的资源中,它也会工作。我错过了什么?

最佳答案

正确:

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

错误:

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

关于xaml - x :Bind in resource dictionary doesn't work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657684/

相关文章:

c# - “System.Reflection.TargetInitationException”(MVVM Light 内部)

c# - 将图像源绑定(bind)到页面

c# - WPF中如何通过代码将字符串绑定(bind)到动态资源

xaml - Xamarin.Forms:动画页面/布局过渡

c# - 基于MVVM的组合框选择的WPF更改窗口布局

c# - CefSharp WPF 和 MVVM?

c# - 如何手动查找仅由 DataType 而不是 key 定义的 DataTemplate?

xamarin - MvvmCross:枚举 MvxRequestedByType 的用途是什么?

android - 身份验证 - Xamarin.Forms、Azure 移动应用

c# - 菜单项内的 Windows 10 UWP 应用程序菜单弹出窗口