我有一个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();
}
}
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的依赖关系,也可以使服务单例qazxsw poi
然后在App.xaml中,为locator添加一个资源:
https://autofaccn.readthedocs.io/en/latest/resolve/index.html
然后在你的页面中(最好不在后面的代码中)你应该像这样分配你的DataContext:
<Application.Resources>
<services:ViewModelLocator x:Key="Locator" />
</Application.Resources>
然后您的ViewModel应如下所示:
<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>
您的对话服务看起来像:
using App1.Services;
namespace App1.ViewModels
{
public class MainPageViewModel
{
private readonly ISpeechDialogService _speechDialogService;
public MainPageViewModel(ISpeechDialogService speechDialogService)
{
_speechDialogService = speechDialogService;
}
}
}
希望这可以帮助。