【发布时间】:2015-08-24 17:35:07
【问题描述】:
我想通过编译绑定将页面中的元素绑定到代码后面的依赖属性,同时使用常规绑定将另一个元素绑定到 ViewModel。但它给出了运行时错误。
这是我的 xaml 代码。
<Page
x:Class="XbindingProblem.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XbindingProblem"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
DataContext="{Binding Main, Source={StaticResource Locator}}"
mc:Ignorable="d">
<Page.Resources>
<DataTemplate x:Key="UserDataTemplate" x:DataType="local:User">
<StackPanel>
<TextBlock Text="{x:Bind Name}" />
<TextBlock Text="{x:Bind Age}" />
</StackPanel>
</DataTemplate>
</Page.Resources>
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBlock Text="{Binding Title}"/>
<ContentPresenter ContentTemplate="{StaticResource UserDataTemplate}" Content="{x:Bind CurrentUser, Mode=OneWay}"/>
</StackPanel>
</Grid>
这里的 CurrentUser 是依赖属性,最初为 null,然后在运行时更改。这会产生以下运行时错误。
Incorrect type passed into template. Based on the x:DataType global::XbindingProblem.User was expected.
问题是当 CurrentUser 为 null 时,它将 ViewModel 传递给 UserDataTemplate 而不是 CurrentUser 依赖属性。
任何人都可以对这个问题有一个很好的解释吗?
【问题讨论】:
标签: c# xaml uwp win-universal-app