c# – 与ViewModel的Windows 10 Universal Compiled binding(x:Bind)冲突

c# – 与ViewModel的Windows 10 Universal Compiled binding(x:Bind)冲突,第1张

概述我想将页面中的元素绑定到带有编译绑定的代码中的依赖属性,同时使用常规绑定将另一个元素绑定到ViewModel.但它给出了运行时错误. 这是我的xaml代码. <Pagex:Class="XbindingProblem.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http: 我想将页面中的元素绑定到带有编译绑定的代码中的依赖属性,同时使用常规绑定将另一个元素绑定到viewmodel.但它给出了运行时错误.

这是我的xaml代码.

<Pagex: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属性外,当然它不会找到它,因此会抛出编译时错误.

一个可能的解决方法是在调用InitializeComponent之前很早就设置this.CurrentUser.

this.CurrentUser = new User();InitializeComponent();

但这是恕我直言,不是正确的做事方式,因为它基本上是一个赛车游戏 – 它试图在DataContext更新之前填充ContentPresenter,最后你将最终得到TextBlock(其中Text绑定到Title) )和ContentPresenter附加到不同的上下文!

那么问问自己为什么需要在Page对象中为CurrentUser创建一个依赖项属性,而不是在Mainviewmodel中有一个普通的属性(使用INotifyPropertyChanged实现)?我更喜欢后者,因为它在语义上更正确.

总结

以上是内存溢出为你收集整理的c# – 与ViewModel的Windows 10 Universal Compiled binding(x:Bind)冲突全部内容,希望文章能够帮你解决c# – 与ViewModel的Windows 10 Universal Compiled binding(x:Bind)冲突所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1219626.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存