PRISM:IDialogService在实现(xamarin)时出现问题

mm5n2pyu  于 2022-12-16  发布在  其他
关注(0)|答案(1)|浏览(196)

我尝试在mvvm中制作IDialogService,因为我需要在视图模型中显示警报。但是我很难获得IDialogService示例,每次我都得到错误或空示例。我不能将其作为ctor中的参数,因为我需要无参数的ctor。
所以我的问题是如何实现IDialogService?
下面是我代码:
调用以显示对话框窗口的方法:

public void ShowAlert(string message, string title)
        {
            var parameters = new DialogParameters
            {
                { "title", title },
                { "message", message }
            };
            _dialogService.ShowDialog("DialogWindow", parameters);
        }

注册对话服务:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
...
containerRegistry.RegisterDialog<DialogWindow>("DialogWindow");
...
}

对话框窗口视图:

<Grid xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             BackgroundColor="white"
             x:Class="Clients.DialogWindow">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <BoxView Color="Black"/>
    <Label Text="{Binding Title}"
           Margin="20,10"
           TextColor="White"/>
    <Label Text="{Binding Message}"
           Margin="20,0,20,10"
           Grid.Row="1" />
    <Button Text="Ok"
            Command="{Binding CloseCommand}"
            HorizontalOptions="Center"
            Margin="10"
            WidthRequest="50"
            Grid.Row="2"/>

</Grid>

对话窗口VM:

class DialogWindowViewModel : BindableBase, IDialogAware
    {

        public DialogWindowViewModel()
        {
            CloseCommand = new DelegateCommand(() => RequestClose(null));
        }
        public event Action<IDialogParameters> RequestClose;

        public DelegateCommand CloseCommand { get; }
        private string title;
        public string Title
        {
            get => title;
            set => SetProperty(ref title, value);
        }

        private string message;
        public string Message
        {
            get => message;
            set => SetProperty(ref message, value);
        }

        public bool CanCloseDialog() => true;

        public void OnDialogClosed()
        {
            //throw new NotImplementedException();
        }

        public void OnDialogOpened(IDialogParameters parameters)
        {
            Message = parameters.GetValue<string>("message");
            Title = parameters.GetValue<string>("title");
        }
    }

感谢您的帮助!

guicsvcw

guicsvcw1#

您可以在构造函数上直接注入对话服务。您可以使用无参数构造函数和其他whit参数。
我用两个构造函数解决了这个问题

public IDialogService _dialogService;
    
public ConstructorViewModel(DialogService dialogService)
{
    _dialogService = dialogService;
}

public ConstructorViewModel()
{
 // Parameterless Constructor
}

相关问题