我正在努力掌握已编译的数据绑定(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/