Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Create a DialogBox to prompt the user for Yes/No option in WPF

Tags:

dialog

wpf

I know how to do this on Windows Form App, but I couldn't find anyway of doing so on a WPF App. How would I present the user a blocking DialogBox with Yes/No option and get/process the response from the user?

like image 677
Shamim Hafiz - MSFT Avatar asked Jun 23 '11 09:06

Shamim Hafiz - MSFT


People also ask

What is dialog box in WPF?

Common dialog boxes As a user uses a common dialog box in one application, they don't need to learn how to use that dialog box in other applications. WPF encapsulates the open file, save file, and print common dialog boxes and exposes them as managed classes for you to use in standalone applications.

Which dialog box does not prevent a user from activating other windows while it is open?

The most common example of the Modal dialog box is Open, Save, and print data. Modeless: The difference between the Modal and Modeless dialog box is that the modeless dialog box does not prevent us to activate the other windows when we try to open the other window.


2 Answers

Here's an example:

string sMessageBoxText = "Do you want to continue?";
string sCaption = "My Test Application";

MessageBoxButton btnMessageBox = MessageBoxButton.YesNoCancel;
MessageBoxImage icnMessageBox = MessageBoxImage.Warning;

MessageBoxResult rsltMessageBox = MessageBox.Show(sMessageBoxText, sCaption, btnMessageBox, icnMessageBox);

switch (rsltMessageBox)
{
    case MessageBoxResult.Yes:
    /* ... */
    break;

    case MessageBoxResult.No:
    /* ... */
    break;

    case MessageBoxResult.Cancel:
    /* ... */
    break;
}
like image 116
rid Avatar answered Oct 01 '22 09:10

rid


Please note that while Radu's answer works, you cannot apply WPF styles to the MessageBox.

I took a different approach to this problem.

I created a class to serve as a View Model for my message window and I created a style for how I wanted my window to appear. Later in code I instantiated a new Window, set it's DataContext to an instance of my View Model, and set the Window's Style property to the style I created for the window.

I know it sounds a bit overkill, and I'm not sure how other people go about solving this same issue... but my solution is quite flexible and I'm starting to really like it.

For example, here is Dialog View Model:

Public Class MyDialogViewModel
  Public Event Closed()

  Public Property Message As String

  Public Property Cancel As MyNamespace.RelayCommand
  Public Property Close As MyNamespace.RelayCommand
  Public Property WasCancelled As Boolean

  Public Sub New()
    WasCancelled = True
    Cancel = New MyNamespace.RelayCommand(AddressOf CancelClicked)
    Close = New MyNamespace.RelayCommand(AddressOf CloseClicked)
  End Sub

  Private Sub CancelClicked()
    RaiseEvent Closed()
  End Sub
  Private Sub CloseClicked()
    WasCancelled = False
    RaiseEvent Closed()
  End Sub
End Class

Here is my style for a basic "message" window:

    <Style x:Key="myMessageStyle" TargetType="{x:Type myNameSpace:CustomDialogWindow}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <ControlTemplate.Resources>
                        <Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
                            <Setter Property="Width" Value="100"/>
                            <Setter Property="Height" Value="25"/>
                        </Style>
                    </ControlTemplate.Resources>
                    <Border >
                        <DockPanel Margin="10,10,0,10">
                            <TextBlock Text="{Binding Message}" Width="Auto" TextWrapping="WrapWithOverflow" DockPanel.Dock="Top" 
                                       Margin="10"
                                       Foreground="{StaticResource MyMessageBoxForegroundColor}"/>
                            <DockPanel Margin="5,0,0,0" DockPanel.Dock="Bottom">
                                <Button Content="Ok" Command="{Binding Close}" ></Button>
                                <Button Content="Cancel" Command="{Binding Cancel}"  HorizontalAlignment="Stretch"></Button>
                            </DockPanel>
                        </DockPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

My CustomDialogWindow is simply a window with nothing in it:

(XAML)

<Window x:Class="CustomDialogWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CustomDialogWindow"
        SizeToContent="WidthAndHeight">

</Window>

And in the CustomDialogWindow I have the following code so that the window closes when the user clicks cancel or ok:

Public Class CustomDialogWindow 

    Private Sub CustomDialogWindow_DataContextChanged(ByVal sender As Object, ByVal e As System.Windows.DependencyPropertyChangedEventArgs) Handles Me.DataContextChanged
        Dim dContext As MyDialogViewModel= TryCast(DataContext, MyDialogViewModel)
        If dContext IsNot Nothing Then
            AddHandler DirectCast(DataContext, MyDialogViewModel).CloseWindow, AddressOf CloseWindow
        End If
    End Sub
    Private Sub CloseWindow()
        Me.Close()
    End Sub
End Class

Now when I need to use the window I just instantiate a new CustomDialogWindow, set it's DataContext to a new instance of the DialogViewModel class, and set it's style to the "myMessageStyle":

Dim cdw As New CustomDialogWindow
Dim dvm As New DialogViewModel
dvm.Message = "Hello World!"
cdw.DataContext = dvm
cdw.ShowDialog()

If dvm.WasCancelled = False Then 
  '....'
End If

The reason why I like this approach is because I inherit from the MyDialogViewModel and provide more properties so that, for instance, I can display a bunch of options for the user to choose from. I just supply custom styles for each type of window I want to display (making sure to bind the appropriate properties). Like I said, it's very flexible and pretty simple to implement.

Cheers!

-Frinny

like image 35
Frinavale Avatar answered Oct 01 '22 09:10

Frinavale