gpt4 book ai didi

c# - MVVMCross如何实现ContentDialog

转载 作者:行者123 更新时间:2023-12-03 10:42:25 25 4
gpt4 key购买 nike

我有一个small example github repo,我想使用 MVVMCross 框架在单击按钮后通过打开自定义的ContentDialog (SpeechDialog)。

如果我使用MVVM 实现了ContentDialog而没有框架,则MainView将如下所示:

public sealed partial class MainView : Page
{
public MainView()
{
this.InitializeComponent();
ISpeechDialogService dialog = new SpeechDialogService();
MainViewModel= new MainViewModel(dialog);
}
public MainViewModel MainViewModel{ get; set; }
}

但是在 MVVMCross 中,我有一个属性MainView,我不知道如何传递ContentDialog:
[MvxViewFor(typeof(MainViewModel))]
public sealed partial class MainView : MvxWindowsPage
{
public MainView()
{
InitializeComponent();
}
}

一些代码可以使您更好地理解:

SpeechDialogService.cs:
public class SpeechDialogService : ISpeechDialogService
{
public async Task ShowAsync()
{
var contentDialog = new Speech();
await contentDialog.ShowAsync();
}

}

directlink to the Speech.xaml

TL; DR

我的方法正确吗?如果是,那么 如何将ContentDialog 传递给MainViewModel?如果不是, 如何使用MVVMCross 实现ContentDialog?

最佳答案

我认为您可以在这里使用ViewModelLocator并使用MVVM模式,而不管框架如何。请参阅示例实现。

public class ViewModelLocator
{
public MainPageViewModel MainPageViewModel
{
get
{
ISpeechDialogService dialogService = new SpeechDialogService();
MainPageViewModel vm = new MainPageViewModel(dialogService);
return vm;
}
}
}

在这里,您可以使用Autofac解决ViewModels的依赖关系,还可以使服务单例 https://autofaccn.readthedocs.io/en/latest/resolve/index.html

然后在您的App.xaml中,为定位器添加资源:
<Application.Resources>
<services:ViewModelLocator x:Key="Locator" />
</Application.Resources>

然后,在页面中(最好不要在后面的代码中),您应该像这样分配DataContext:
<Page
x:Class="App1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
d:DesignHeight="450" d:DesignWidth="800"
DataContext="{Binding MainPageViewModel, Source={StaticResource Locator}}">

</Page>

然后,您的ViewModel应该看起来像:
using App1.Services;

namespace App1.ViewModels
{
public class MainPageViewModel
{
private readonly ISpeechDialogService _speechDialogService;
public MainPageViewModel(ISpeechDialogService speechDialogService)
{
_speechDialogService = speechDialogService;
}
}
}

您的对话框服务如下所示:
using System.Threading.Tasks;

namespace App1.Services
{
public class SpeechDialogService : ISpeechDialogService
{
public async Task ShowAsync()
{
var contentDialog = new Speech();
await contentDialog.ShowAsync();
}
}
}

希望这可以帮助。

关于c# - MVVMCross如何实现ContentDialog,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52127617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com