punker76 / MahApps.Metro.CustomDialog.Sample

Sample for a custom Dialog with MahApps.Metro
MIT License
11 stars 4 forks source link

It seems like breaking MVVM #1

Open GF-Huang opened 5 years ago

GF-Huang commented 5 years ago

It seems like breaking MVVM, because there's VM codes inside code-behind.

image

TechnikEmpire commented 5 years ago

This isn't breaking MVVM, it's called being a good programmer and not sticking to some ultra-strict interpretation of design patterns. Have you tried doing the same thing but inside the view model? Good luck. When your "right" solution takes twice as much code, it's the wrong solution.

nathanpovo commented 3 years ago

Given that this repository is just a sample, the author might not have wanted to make the code harder to understand (for people who are not familiar with the MVVM pattern).

But, you can easily make the sample follow the MVVM pattern a bit more strictly by updating the MainView.xaml to:

<controls:MetroWindow x:Class="MahApps.CustomDialog.Sample.MainView"
                      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                      xmlns:controls="http://metro.mahapps.com/winfx/xaml/controls"
                      mc:Ignorable="d"
                      Title="MainWindow" Height="600" Width="800" WindowStartupLocation="CenterScreen"
                      GlowBrush="{DynamicResource AccentBaseColorBrush}">
    <Grid>
        <Button Content="Yes or No..."
                Padding="15"
                HorizontalAlignment="Center"
                VerticalAlignment="Center"
                Command="{Binding ShowDialog}" />
    </Grid>
</controls:MetroWindow>

and the MainViewModel.cs to:

using System.Windows.Input;
using TinyLittleMvvm;

namespace MahApps.CustomDialog.Sample
{
    public class MainViewModel : PropertyChangedBase, IShell
    {
        private readonly IDialogManager _dialogManager;

        public MainViewModel(IDialogManager dialogManager)
        {
            _dialogManager = dialogManager;

            ShowDialog = new RelayCommand(OnDialogCommandExecute);
        }

        public ICommand ShowDialog { get; }

        private async void OnDialogCommandExecute()
        {
            var dialogViewModel = new ChoiceDialogViewModel();
            dialogViewModel.Title = "What's your choice?";
            dialogViewModel.Message = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt?";

            var result = await _dialogManager.ShowDialogAsync(dialogViewModel);

            await _dialogManager.ShowMessageBox("Result", $"Your choice was: {result}");
        }
    }
}

Then just remove the ButtonOnClick method from the view's code behind.