Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well not exactly an answer to my question, but here is the result of doing this dialog, complete with code so you can use it if you wish - free as in free speech and beer:</p> <p><img src="https://i.stack.imgur.com/BYEcL.png" alt="MVVM dialog modal only inside the containing view"></p> <p><strong>XAML Usage in another view (here CustomerView):</strong></p> <pre><code>&lt;UserControl x:Class="DemoApp.View.CustomerView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:controls="clr-namespace:DemoApp.View" &gt; &lt;Grid&gt; &lt;Grid Margin="4" x:Name="ModalDialogParent"&gt; &lt;put all view content here/&gt; &lt;/Grid&gt; &lt;controls:ModalDialog DataContext="{Binding Dialog}" OverlayOn="{Binding ElementName=ModalDialogParent, Mode=OneWay}" IsShown="{Binding Path=DialogShown}"/&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p><strong>Triggering from parent ViewModel (here CustomerViewModel):</strong></p> <pre><code> public ModalDialogViewModel Dialog // dialog view binds to this { get { return _dialog; } set { _dialog = value; base.OnPropertyChanged("Dialog"); } } public void AskSave() { Action OkCallback = () =&gt; { if (Dialog != null) Dialog.Hide(); Save(); }; if (Email.Length &lt; 10) { Dialog = new ModalDialogViewModel("This email seems a bit too short, are you sure you want to continue saving?", ModalDialogViewModel.DialogButtons.Ok, ModalDialogViewModel.CreateCommands(new Action[] { OkCallback })); Dialog.Show(); return; } if (LastName.Length &lt; 2) { Dialog = new ModalDialogViewModel("The Lastname seems short. Are you sure that you want to save this Customer?", ModalDialogViewModel.CreateButtons(ModalDialogViewModel.DialogMode.TwoButton, new string[] {"Of Course!", "NoWay!"}, OkCallback, () =&gt; Dialog.Hide())); Dialog.Show(); return; } Save(); // if we got here we can save directly } </code></pre> <p><strong><em>Here is the code:</em></strong></p> <p><strong>ModalDialogView XAML:</strong></p> <pre><code> &lt;UserControl x:Class="DemoApp.View.ModalDialog" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Name="root"&gt; &lt;UserControl.Resources&gt; &lt;ResourceDictionary Source="../MainWindowResources.xaml" /&gt; &lt;/UserControl.Resources&gt; &lt;Grid&gt; &lt;Border Background="#90000000" Visibility="{Binding Visibility}"&gt; &lt;Border BorderBrush="Black" BorderThickness="1" Background="AliceBlue" CornerRadius="10,0,10,0" VerticalAlignment="Center" HorizontalAlignment="Center"&gt; &lt;Border.BitmapEffect&gt; &lt;DropShadowBitmapEffect Color="Black" Opacity="0.5" Direction="270" ShadowDepth="0.7" /&gt; &lt;/Border.BitmapEffect&gt; &lt;Grid Margin="10"&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition /&gt; &lt;RowDefinition /&gt; &lt;RowDefinition Height="Auto" /&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Style="{StaticResource ModalDialogHeader}" Text="{Binding DialogHeader}" Grid.Row="0"/&gt; &lt;TextBlock Text="{Binding DialogMessage}" Grid.Row="1" TextWrapping="Wrap" Margin="5" /&gt; &lt;StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Grid.Row="2"&gt; &lt;ContentControl HorizontalAlignment="Stretch" DataContext="{Binding Commands}" Content="{Binding}" ContentTemplate="{StaticResource ButtonCommandsTemplate}" /&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Border&gt; &lt;/Border&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p><strong>ModalDialogView code behind:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Windows; using System.Windows.Controls; using System.Windows.Data; namespace DemoApp.View { /// &lt;summary&gt; /// Interaction logic for ModalDialog.xaml /// &lt;/summary&gt; public partial class ModalDialog : UserControl { public ModalDialog() { InitializeComponent(); Visibility = Visibility.Hidden; } private bool _parentWasEnabled = true; public bool IsShown { get { return (bool)GetValue(IsShownProperty); } set { SetValue(IsShownProperty, value); } } // Using a DependencyProperty as the backing store for IsShown. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsShownProperty = DependencyProperty.Register("IsShown", typeof(bool), typeof(ModalDialog), new UIPropertyMetadata(false, IsShownChangedCallback)); public static void IsShownChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { if ((bool)e.NewValue == true) { ModalDialog dlg = (ModalDialog)d; dlg.Show(); } else { ModalDialog dlg = (ModalDialog)d; dlg.Hide(); } } #region OverlayOn public UIElement OverlayOn { get { return (UIElement)GetValue(OverlayOnProperty); } set { SetValue(OverlayOnProperty, value); } } // Using a DependencyProperty as the backing store for Parent. This enables animation, styling, binding, etc... public static readonly DependencyProperty OverlayOnProperty = DependencyProperty.Register("OverlayOn", typeof(UIElement), typeof(ModalDialog), new UIPropertyMetadata(null)); #endregion public void Show() { // Force recalculate binding since Show can be called before binding are calculated BindingExpression expressionOverlayParent = this.GetBindingExpression(OverlayOnProperty); if (expressionOverlayParent != null) { expressionOverlayParent.UpdateTarget(); } if (OverlayOn == null) { throw new InvalidOperationException("Required properties are not bound to the model."); } Visibility = System.Windows.Visibility.Visible; _parentWasEnabled = OverlayOn.IsEnabled; OverlayOn.IsEnabled = false; } private void Hide() { Visibility = Visibility.Hidden; OverlayOn.IsEnabled = _parentWasEnabled; } } } </code></pre> <p><strong>ModalDialogViewModel:</strong></p> <pre><code>using System; using System.Windows.Input; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Windows; using System.Linq; namespace DemoApp.ViewModel { /// &lt;summary&gt; /// Represents an actionable item displayed by a View (DialogView). /// &lt;/summary&gt; public class ModalDialogViewModel : ViewModelBase { #region Nested types /// &lt;summary&gt; /// Nested enum symbolizing the types of default buttons used in the dialog -&gt; you can localize those with Localize(DialogMode, string[]) /// &lt;/summary&gt; public enum DialogMode { /// &lt;summary&gt; /// Single button in the View (default: OK) /// &lt;/summary&gt; OneButton = 1, /// &lt;summary&gt; /// Two buttons in the View (default: YesNo) /// &lt;/summary&gt; TwoButton, /// &lt;summary&gt; /// Three buttons in the View (default: AbortRetryIgnore) /// &lt;/summary&gt; TreeButton, /// &lt;summary&gt; /// Four buttons in the View (no default translations, use Translate) /// &lt;/summary&gt; FourButton, /// &lt;summary&gt; /// Five buttons in the View (no default translations, use Translate) /// &lt;/summary&gt; FiveButton } /// &lt;summary&gt; /// Provides some default button combinations /// &lt;/summary&gt; public enum DialogButtons { /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration Ok /// &lt;/summary&gt; Ok, /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration OkCancel /// &lt;/summary&gt; OkCancel, /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration YesNo /// &lt;/summary&gt; YesNo, /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration YesNoCancel /// &lt;/summary&gt; YesNoCancel, /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration AbortRetryIgnore /// &lt;/summary&gt; AbortRetryIgnore, /// &lt;summary&gt; /// As System.Window.Forms.MessageBoxButtons Enumeration RetryCancel /// &lt;/summary&gt; RetryCancel } #endregion #region Members private static Dictionary&lt;DialogMode, string[]&gt; _translations = null; private bool _dialogShown; private ReadOnlyCollection&lt;CommandViewModel&gt; _commands; private string _dialogMessage; private string _dialogHeader; #endregion #region Class static methods and constructor /// &lt;summary&gt; /// Creates a dictionary symbolizing buttons for given dialog mode and buttons names with actions to berform on each /// &lt;/summary&gt; /// &lt;param name="mode"&gt;Mode that tells how many buttons are in the dialog&lt;/param&gt; /// &lt;param name="names"&gt;Names of buttons in sequential order&lt;/param&gt; /// &lt;param name="callbacks"&gt;Callbacks for given buttons&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; public static Dictionary&lt;string, Action&gt; CreateButtons(DialogMode mode, string[] names, params Action[] callbacks) { int modeNumButtons = (int)mode; if (names.Length != modeNumButtons) throw new ArgumentException("The selected mode needs a different number of button names", "names"); if (callbacks.Length != modeNumButtons) throw new ArgumentException("The selected mode needs a different number of callbacks", "callbacks"); Dictionary&lt;string, Action&gt; buttons = new Dictionary&lt;string, Action&gt;(); for (int i = 0; i &lt; names.Length; i++) { buttons.Add(names[i], callbacks[i]); } return buttons; } /// &lt;summary&gt; /// Static contructor for all DialogViewModels, runs once /// &lt;/summary&gt; static ModalDialogViewModel() { InitTranslations(); } /// &lt;summary&gt; /// Fills the default translations for all modes that we support (use only from static constructor (not thread safe per se)) /// &lt;/summary&gt; private static void InitTranslations() { _translations = new Dictionary&lt;DialogMode, string[]&gt;(); foreach (DialogMode mode in Enum.GetValues(typeof(DialogMode))) { _translations.Add(mode, GetDefaultTranslations(mode)); } } /// &lt;summary&gt; /// Creates Commands for given enumeration of Actions /// &lt;/summary&gt; /// &lt;param name="actions"&gt;Actions to create commands from&lt;/param&gt; /// &lt;returns&gt;Array of commands for given actions&lt;/returns&gt; public static ICommand[] CreateCommands(IEnumerable&lt;Action&gt; actions) { List&lt;ICommand&gt; commands = new List&lt;ICommand&gt;(); Action[] actionArray = actions.ToArray(); foreach (var action in actionArray) { //RelayExecuteWrapper rxw = new RelayExecuteWrapper(action); Action act = action; commands.Add(new RelayCommand(x =&gt; act())); } return commands.ToArray(); } /// &lt;summary&gt; /// Creates string for some predefined buttons (English) /// &lt;/summary&gt; /// &lt;param name="buttons"&gt;DialogButtons enumeration value&lt;/param&gt; /// &lt;returns&gt;String array for desired buttons&lt;/returns&gt; public static string[] GetButtonDefaultStrings(DialogButtons buttons) { switch (buttons) { case DialogButtons.Ok: return new string[] { "Ok" }; case DialogButtons.OkCancel: return new string[] { "Ok", "Cancel" }; case DialogButtons.YesNo: return new string[] { "Yes", "No" }; case DialogButtons.YesNoCancel: return new string[] { "Yes", "No", "Cancel" }; case DialogButtons.RetryCancel: return new string[] { "Retry", "Cancel" }; case DialogButtons.AbortRetryIgnore: return new string[] { "Abort", "Retry", "Ignore" }; default: throw new InvalidOperationException("There are no default string translations for this button configuration."); } } private static string[] GetDefaultTranslations(DialogMode mode) { string[] translated = null; switch (mode) { case DialogMode.OneButton: translated = GetButtonDefaultStrings(DialogButtons.Ok); break; case DialogMode.TwoButton: translated = GetButtonDefaultStrings(DialogButtons.YesNo); break; case DialogMode.TreeButton: translated = GetButtonDefaultStrings(DialogButtons.YesNoCancel); break; default: translated = null; // you should use Translate() for this combination (ie. there is no default for four or more buttons) break; } return translated; } /// &lt;summary&gt; /// Translates all the Dialogs with specified mode /// &lt;/summary&gt; /// &lt;param name="mode"&gt;Dialog mode/type&lt;/param&gt; /// &lt;param name="translations"&gt;Array of translations matching the buttons in the mode&lt;/param&gt; public static void Translate(DialogMode mode, string[] translations) { lock (_translations) { if (translations.Length != (int)mode) throw new ArgumentException("Wrong number of translations for selected mode"); if (_translations.ContainsKey(mode)) { _translations.Remove(mode); } _translations.Add(mode, translations); } } #endregion #region Constructors and initialization public ModalDialogViewModel(string message, DialogMode mode, params ICommand[] commands) { Init(message, Application.Current.MainWindow.GetType().Assembly.GetName().Name, _translations[mode], commands); } public ModalDialogViewModel(string message, DialogMode mode, params Action[] callbacks) { Init(message, Application.Current.MainWindow.GetType().Assembly.GetName().Name, _translations[mode], CreateCommands(callbacks)); } public ModalDialogViewModel(string message, Dictionary&lt;string, Action&gt; buttons) { Init(message, Application.Current.MainWindow.GetType().Assembly.GetName().Name, buttons.Keys.ToArray(), CreateCommands(buttons.Values.ToArray())); } public ModalDialogViewModel(string message, string header, Dictionary&lt;string, Action&gt; buttons) { if (buttons == null) throw new ArgumentNullException("buttons"); ICommand[] commands = CreateCommands(buttons.Values.ToArray&lt;Action&gt;()); Init(message, header, buttons.Keys.ToArray&lt;string&gt;(), commands); } public ModalDialogViewModel(string message, DialogButtons buttons, params ICommand[] commands) { Init(message, Application.Current.MainWindow.GetType().Assembly.GetName().Name, ModalDialogViewModel.GetButtonDefaultStrings(buttons), commands); } public ModalDialogViewModel(string message, string header, DialogButtons buttons, params ICommand[] commands) { Init(message, header, ModalDialogViewModel.GetButtonDefaultStrings(buttons), commands); } public ModalDialogViewModel(string message, string header, string[] buttons, params ICommand[] commands) { Init(message, header, buttons, commands); } private void Init(string message, string header, string[] buttons, ICommand[] commands) { if (message == null) throw new ArgumentNullException("message"); if (buttons.Length != commands.Length) throw new ArgumentException("Same number of buttons and commands expected"); base.DisplayName = "ModalDialog"; this.DialogMessage = message; this.DialogHeader = header; List&lt;CommandViewModel&gt; commandModels = new List&lt;CommandViewModel&gt;(); // create commands viewmodel for buttons in the view for (int i = 0; i &lt; buttons.Length; i++) { commandModels.Add(new CommandViewModel(buttons[i], commands[i])); } this.Commands = new ReadOnlyCollection&lt;CommandViewModel&gt;(commandModels); } #endregion #region Properties /// &lt;summary&gt; /// Checks if the dialog is visible, use Show() Hide() methods to set this /// &lt;/summary&gt; public bool DialogShown { get { return _dialogShown; } private set { _dialogShown = value; base.OnPropertyChanged("DialogShown"); } } /// &lt;summary&gt; /// The message shown in the dialog /// &lt;/summary&gt; public string DialogMessage { get { return _dialogMessage; } private set { _dialogMessage = value; base.OnPropertyChanged("DialogMessage"); } } /// &lt;summary&gt; /// The header (title) of the dialog /// &lt;/summary&gt; public string DialogHeader { get { return _dialogHeader; } private set { _dialogHeader = value; base.OnPropertyChanged("DialogHeader"); } } /// &lt;summary&gt; /// Commands this dialog calls (the models that it binds to) /// &lt;/summary&gt; public ReadOnlyCollection&lt;CommandViewModel&gt; Commands { get { return _commands; } private set { _commands = value; base.OnPropertyChanged("Commands"); } } #endregion #region Methods public void Show() { this.DialogShown = true; } public void Hide() { this._dialogMessage = String.Empty; this.DialogShown = false; } #endregion } } </code></pre> <p>ViewModelBase has :</p> <p><code>public virtual string DisplayName { get; protected set; }</code></p> <p>and implements <code>INotifyPropertyChanged</code></p> <p><strong>Some resources to put in the resource dictionary:</strong></p> <pre><code>&lt;!-- This style gives look to the dialog head (used in the modal dialog) --&gt; &lt;Style x:Key="ModalDialogHeader" TargetType="{x:Type TextBlock}"&gt; &lt;Setter Property="Background" Value="{StaticResource Brush_HeaderBackground}" /&gt; &lt;Setter Property="Foreground" Value="White" /&gt; &lt;Setter Property="Padding" Value="4" /&gt; &lt;Setter Property="HorizontalAlignment" Value="Stretch" /&gt; &lt;Setter Property="Margin" Value="5" /&gt; &lt;Setter Property="TextWrapping" Value="NoWrap" /&gt; &lt;/Style&gt; &lt;!-- This template explains how to render the list of commands as buttons (used in the modal dialog) --&gt; &lt;DataTemplate x:Key="ButtonCommandsTemplate"&gt; &lt;ItemsControl IsTabStop="False" ItemsSource="{Binding}" Margin="6,2"&gt; &lt;ItemsControl.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;Button MinWidth="75" Command="{Binding Path=Command}" Margin="4" HorizontalAlignment="Right"&gt; &lt;TextBlock Text="{Binding Path=DisplayName}" Margin="2"&gt;&lt;/TextBlock&gt; &lt;/Button&gt; &lt;/DataTemplate&gt; &lt;/ItemsControl.ItemTemplate&gt; &lt;ItemsControl.ItemsPanel&gt; &lt;ItemsPanelTemplate&gt; &lt;StackPanel Orientation="Horizontal" HorizontalAlignment="Center" /&gt; &lt;/ItemsPanelTemplate&gt; &lt;/ItemsControl.ItemsPanel&gt; &lt;/ItemsControl&gt; &lt;/DataTemplate&gt; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload