2016-11-17 67 views
2

我正在努力掌握已编译的数据绑定概念。我有一个视图(MainPage),它包含一个ListBox和一个用于该ListBox的数据模板(ItemTemplate)。 MainPage有一个MainPageViewModel,它包含一个ItemViewModels的ObservableCollection。 ItemViewModel只包含一个属性名称。x:在资源字典中绑定不起作用

的MainPage:含有的DataTemplate

<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属性会失败,尽管获取生成的项目。如果我使用经典的绑定,一切正常,如果我直接将数据模板放置在MainPage的资源中,它也可以工作。我错过了什么?

+4

也许有所帮助:http://igrali.com/2015/06/14/how-to-use-compiled-bindings-xbind- from-a-resource-dictionary/ – Clemens

+0

Bind是一个编译时构造,IIRC。但是DataTemplate中的所有内容都是运行时的 - 它不是硬编码到窗口中,而是根据需要在运行时动态加载。我没有任何引用告诉我这一点,但我假设x:绑定在运行时没有挂钩。将其切换到常规绑定。这有点像一个StaticResoruce如何在编译时可用于可用内容,但是当您尝试查找运行时集资源时,您必须使用DynamicResource。 – Will

+0

@ will但根据文档,它应该工作,如果x:DataType声明。请参阅[DataTemplate和x:DataType](https://msdn.microsoft.com/windows/uwp/data-binding/data-binding-in-depth#binding_object_xbind) –

回答

2

正确:

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