Kri*_*ast 2 xaml mvvm compiled-bindings uwp xbind
我正在努力掌握已编译的数据绑定概念。我有一个视图 (MainPage),其中包含一个 ListBox 和一个用于该 ListBox 的数据模板 (ItemTemplate)。MainPage 有一个 MainPageViewModel,其中包含一个 ObservableCollection 的 ItemViewModel。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>
Run Code Online (Sandbox Code Playgroud)
包含数据模板的资源字典:
<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>
Run Code Online (Sandbox Code Playgroud)
这段代码可以编译,但是当我运行它时,与 Name 属性的绑定失败,尽管生成了项目。如果我使用经典绑定,一切正常,如果我将数据模板直接放在 MainPage 的资源中,它也可以正常工作。我错过了什么?
正确的:
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<local:ItemDictionary />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
Run Code Online (Sandbox Code Playgroud)
不正确:
<Page.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ItemDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
613 次 |
| 最近记录: |