加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 与ViewModel的Windows 10 Universal Compiled binding(x:

发布时间:2020-12-15 23:26:57 所属栏目:百科 来源:网络整理
导读:我想将页面中的元素绑定到带有编译绑定的代码中的依赖属性,同时使用常规绑定将另一个元素绑定到ViewModel.但它给出了运行时错误. 这是我的xaml代码. Pagex:Class="XbindingProblem.MainPage"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentati
我想将页面中的元素绑定到带有编译绑定的代码中的依赖属性,同时使用常规绑定将另一个元素绑定到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属性外,当然它不会找到它,因此会抛出编译时错误.

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

this.CurrentUser = new User();

InitializeComponent();

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读