【问题标题】:MVVM in Universal Windows Platform problem binding通用 Windows 平台问题绑定中的 MVVM
【发布时间】:2023-03-22 05:12:02
【问题描述】:

好的,我正在使用 Visual Studio 和 uwp。我创建了一个 WeatheVM,以作为资源绑定到我的页面。每次我创建资源时,它都说“无法创建 WeatheVM”我很沮丧,我不明白为什么不让我,我需要这个来访问我的属性。

<Page x:Class="uwpMVVM.View.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:uwpMVVM.View"
      xmlns:vm="using:uwpMVVM.ViewModel"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      mc:Ignorable="d"
      Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <Page.Resources>
        <vm:WeatherVM x:Key="vm" />
    </Page.Resources>

    <Grid>

        <AutoSuggestBox x:Name="box"
                        Grid.Column="1"
                        Margin="40"
                        QueryIcon="Find"
                        />
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="53*" />
            <ColumnDefinition Width="247*" />
        </Grid.ColumnDefinitions>

    </Grid>
</Page>

顺便说一句,我的虚拟机是一个公共类

【问题讨论】:

    标签: mvvm uwp binding


    【解决方案1】:

    在您提供的代码中,我看到您在Page.Resources 中创建了WeathVM 的实例,但没有引用它。

    您可以将 Grid 的 DataContext 设置为 vm,以便您可以导入您创建的资源。

    <Grid DataContext="{StaticResource vm}">
        <!-- Other code -->
    </Grid>
    

    假设您有一个要显示的Temp 属性。设置好DataContext后,就可以这样绑定了。

    <Grid DataContext="{StaticResource vm}">
        <TextBlock Text={Binding Temp} />
    </Grid>
    

    这是complete MVVM example,可以参考修改。

    最好的问候。

    【讨论】:

    • 我知道,但是如果 Visual Studio 一直告诉我“无法创建 WeatheVM”,我就不能这样做 因为我有几个类,所以将它创建为资源键是有意义的,那么我可以做点什么like:将网格的数据上下文绑定到 Weather.currentObservations
    • 我按照你说的放了DataContext,同样的错误
    • 您好,能否提供您当前页面的 WeatherVM 代码和 Code-behind,有助于问题分析?
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多