c# - Windows 10 通用编译绑定(bind) (x :Bind) conflict with ViewModel

标签 c# xaml uwp win-universal-app

我想使用编译绑定(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 确实是您页面的依赖属性,因此它会正常工作。

但是,通过指定页面的 DataContextx: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/

相关文章:

c# - 如何在 C# 中创建 TreeView 首选项对话框类型的界面?

c# - 如何从 C# 文件中加载 UWP 格式的图像

c# - Xamarin Form - 如何在 UWP 中以 PDF 或 JPEG 格式存储图像

c# - 以编程方式获取打开的 Excel/Word 文档的路径

c# - 无法将 [] 索引应用于从 NHibernate 返回的对象数组的表达式类型 'object'

c++ - 在 C++ winrt 导航 View 中,如何找到已选择/单击的导航项?

c# - 执行 RenderTransform(缩放和平移)后如何获得 UIElement 的新位置和大小?

c# - 在 c# 中删除 listBoxItem 时 ListBox 不刷新

c# - 应该如何实现 WinRT 对象中的异步回调?

c# - 在 XAML (UWP) 中绑定(bind)单例