如何从ContentDialog导航到使用Template10 MVVM的UWP中的其他页面?

如何解决如何从ContentDialog导航到使用Template10 MVVM的UWP中的其他页面?

LoginPageCD.xaml

<ContentDialog
x:Class="ScanWorx.ContentDialogs.LoginPageCD"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ScanWorx.ContentDialogs"
xmlns:vm="using:ScanWorx.ViewModels"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
x:Name="LoginPageContentD"
SecondaryButtonText="close"
SecondaryButtonClick="LoginPageContentD_SecondaryButtonClick">

<ContentDialog.Resources>
    <Thickness x:Key="ContentDialogPadding">16,16,16</Thickness>
    <vm:LoginPageCDViewModel x:Key="CDViewModel"  />
</ContentDialog.Resources>

<!--  Content Dialog Title  -->
<ContentDialog.TitleTemplate>
    <DataTemplate >

        <TextBlock
            HEADER DATA FOR TEMPLATE/>

    </DataTemplate>
</ContentDialog.TitleTemplate>

<ContentControl x:Name="LoginPageContentControl" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ContentControl.ContentTemplate>
        <DataTemplate>
            <Grid Width="500" Height="500">
                <Grid.RowDefinitions>
                    <RowDefinition />
                    <RowDefinition />
                    <RowDefinition Height="1*" />
                </Grid.RowDefinitions>

                <ComboBox
                    x:Name="Combobox_Login_test"
                    Grid.Row="0"
                    Header="Combobox_Login.Header"
                    IsEditable="True"
                    ItemsSource = "{Binding UserNameList,Source = {StaticResource CDViewModel}}" 
                    Text="{Binding Name,Source = {StaticResource CDViewModel},FallbackValue=DesigntimeValue,Mode=TwoWay}"/>

                <PasswordBox
                    x:Name="PasswordBox_Login"
                    Grid.Row="1"
                    Header="PasswordBox_Login.Header"
                    Password="{Binding Passwort,Mode=TwoWay,Source= {StaticResource CDViewModel}}" />

                <Button
                    x:Name="Button_Login_Click"
                    Grid.Row="2"
                    Command="{Binding LoginButtonCommand,Source= {StaticResource CDViewModel}}"
                    Style="{ThemeResource AccentButtonStyle}"/>

            </Grid>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

LoginPageCD.xaml.cs 代码背后

using ScanWorx.ViewModels;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.ApplicationModel.Resources;
using Template10.Mvvm;

namespace ScanWorx.ContentDialogs
{

public partial class LoginPageCD : ContentDialog
{

    public LoginPResult Result { get; set; }

    public static ResourceLoader dict;
    public LoginPageCD()
    {
        this.InitializeComponent();
        ViewModelBase viewModelBase = new LoginPageCDViewModel();
        this.DataContext = viewModelBase;
        dict = ResourceLoader.GetForCurrentView("Login");
        LoginPageCDViewModel LPVM = new LoginPageCDViewModel();
        LPVM.UpdateUserNameList();
    }


    private void LoginPageContentD_SecondaryButtonClick(ContentDialog sender,ContentDialogButtonClickEventArgs args)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        rootFrame = new Frame();
        Window.Current.Content = rootFrame;
        rootFrame.Navigate(typeof(Views.LoginPage));

        LoginPageContentD.Hide();
       
    }

}
}

LoginPageCDViewModel.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using Template10.Mvvm;
using Template10.Services.NavigationService;
using Windows.ApplicationModel.Resources;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.UI.Popups;
using Windows.UI.Xaml.Navigation;
using System.Linq;
using Windows.UI.Xaml;
using Template10.Utils;

namespace ScanWorx.ViewModels
{
class LoginPageCDViewModel : ViewModelBase
{
    public static ObservableCollection<string> _UserNameList = new ObservableCollection<string>();
    public ObservableCollection<string> UserNameList { get { return _UserNameList; } set { Set(ref _UserNameList,value); } }

    private string _Name = "";
    private string _Passwort = "";

    public RelayCommand LoginButtonCommand
    {
        get;
        private set;
    }

    public string Name { get { return _Name; } set { Set(ref _Name,value); } }
    public string Passwort { get { return _Passwort; } set { Set(ref _Passwort,value); } }


    public static ResourceLoader dict;

    public ObservableCollection<string> UpdateUserNameList()
    {
        try
        {
            **A FUNCTION TO UPDATE THE USER's LIST IN THE COMBOBOX**
            **USAGE: USED IN CODE BEHIND WHILE INITIALIZING THE CONTENT DIALOG**
        }
        catch
        {
            Debug.WriteLine("Catch Exeption:  LoginPage.xaml.cs     Invalid UserManagement.xml file");
        }
        return _UserNameList;
    }

    public LoginPageCDViewModel()
    {
        if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
        {
            Value = "Designtime value";
        }
        Services.SettingsServices.SettingsService.Instance.IsFullScreen = true;

        LoginButtonCommand = new RelayCommand(Button_Login_Click,() => true);

        dict = ResourceLoader.GetForCurrentView("Login");
    }
 
    public async void Button_Login_Click()
    {
        try
        {
                **ACTION: some code to check the username and password**

                loginPageCDViewModel.navigatetomain();        //<<<<// a function to navigate to main page which doesnt work     
                //NavigationService.Navigate(typeof(Views.MainPage));

        }
        catch
        {
            Debug.WriteLine("Catch Exeption:  LoginPageCDViewModel.cs     Button_Login_Click");
        }
    }

    public void navigatetomain()
    {
        Frame rootFrame = Window.Current.Content as Frame;
        rootFrame = new Frame();
        Window.Current.Content = rootFrame;
        rootFrame.Navigate(typeof(Views.MainPage));
        LoginPageContentD.Hide();

        //NavigationService.Navigate(typeof(Views.MainPage));

    }
}
}
  • 以上工作是我尝试过的。我还尝试使用NavigationService.Navigate(typeof(Views.MainPage));导航到主页,但是它也无法正常工作。
  • 感谢您的帮助
  • 我可以使用功能navigatetomain()导航到主页,但是即使我尝试Hide();,内容对话框也不会关闭,而且导航后我也看不到自己的汉堡菜单主页只是一个空白的主页。

注意:后面代码中用于关闭按钮的Hide();很完美。

解决方法

我正在查看您的代码,但是它似乎注释掉了一些内容。这是我的一些想法:

  1. 保持ViewModel的唯一性

我注意到您在ContentDialog相关代码中创建了3个LoginPageCDViewModel,即ContentDialog.ResourcesviewModelBaseLPVM

这可能会引起混乱,您可以尝试仅创建一个LoginPageCDViewModel并将其设置为DataContext,可以在XAML中对其进行绑定。

  1. 未知引用LoginPageContentD

当您尝试关闭ContentDialog时,使用的代码为LoginPageContentD.Hide()。但是我在您提供的代码中找不到此变量的定义。

它是否引用当前的ContentDialog?您可以使用调试断点来跟踪代码,以查看引用是否正常。

  • 如果在ContentDialog中调用它,则可以直接使用this.Hide()
  • 如果这是代表当前ContentDialog实例的变量,则在启动ContentDialog时应为其分配一个值,例如:
public LoginPageCD()
{
    this.InitializeComponent();
    ViewModelBase viewModelBase = new LoginPageCDViewModel();
    this.DataContext = viewModelBase;
    dict = ResourceLoader.GetForCurrentView("Login");
    viewModelBase.UpdateUserNameList();

    viewModelBase.LoginPageContentD = this;
}

如果上述建议不能解决您的问题,您能否提供一个最低限度的可运行演示(不包含私人信息,但可以运行并重现问题),以便我们可以测试和分析原因?

,

我没有使用自己的按钮[Button_Login_click],而是使用contentdialog的primarybuttonclick并使用了LoginPageCDViewModel.cs中声明的relaycommand我将primarybuttoncommand属性绑定到了LoginPageCDViewModel.cs中声明的relaycommand按钮上。

所以现在我的LoginPageCD.xaml看起来像

<ContentDialog
    x:Class="ScanWorx.ContentDialogs.LoginPageCD"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:ScanWorx.ContentDialogs"
    xmlns:vm="using:ScanWorx.ViewModels"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    x:Name="LoginPageContentD"
    PrimaryButtonCommand="{x:Bind Path=vm:LoginPageViewModel.LoginButtonCommand }"
    PrimaryButtonText="Login"
    SecondaryButtonText="close"
    SecondaryButtonClick="LoginPageContentD_SecondaryButtonClick">
   .
   .
   .

,为了导航到所需页面,我利用contentdialog框的结果,即我在应用程序启动时调用ShowAsync();,并在识别出主要点击后使用{{1} }进行导航。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-