我想使用编译绑定(bind)将页面中的元素绑定(bind)到代码隐藏中的依赖属性,同时使用常规绑定(bind)将另一个元素绑定(bind)到 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 依赖属性。
谁能对这个问题有一个很好的解释?
最佳答案
如果您删除 DataContext="{Binding Main, Source={StaticResource Locator}}"
,它将起作用。为什么?因为 {x:Bind CurrentUser}
正在寻找位于 MainPage.xaml.cs
中的名为 CurrentUser
的属性。由于 CurrentUser
确实是您页面的依赖属性,因此它会正常工作。
但是,通过指定页面的 DataContext
,x:Bind
现在除了 MainViewModel 中的
实例,当然它不会找到它,因此会抛出编译时错误。CurrentUser
属性
一个可能的解决方法是尽早设置 this.CurrentUser
,甚至在调用 InitializeComponent
之前。
this.CurrentUser = new User();
InitializeComponent();
但恕我直言,这不是正确的做事方式,因为它基本上是一款赛车游戏 - 它试图在 DataContext
更新之前填充 ContentPresenter
,并且最后,您将得到 TextBlock
(其中 Text
绑定(bind)到 Title
)和附加的 ContentPresenter
到不同的上下文!
所以问问自己为什么需要在 Page
对象中为 CurrentUser
创建一个依赖属性,而不是拥有一个普通属性(使用 INotifyPropertyChanged
实现)坐在你的 MainViewModel
中?我更喜欢后者,因为它在语义上更正确。
关于c# - Windows 10 通用编译绑定(bind) (x :Bind) conflict with ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32188269/