I have two Prism modules.
I want one of them register a window and the other one show this window using the "Show Dialog" mode.
How can it be done (if it can be done)?
Yes, it can be done. This is rough procedure:
Declare interface for this View in your "Infrastructure" project
public interface IMyDialogWindow
{
}
[Export] class that implements this interface in your module
[Export(typeof(IMyDialogWindow))]
public class MyClassInModuleA : IMyDialogWindow
{
}
[Import] this class in other module and use it for Dialog
[Import]
public IMyDialogWindow PropertyInModuleB
Well. I think I solved it by following this tip. But I don't know if it was the best solution.
I just created a window on my Shell project. This window is the one that will be popped up as a dialog window.
Here is its code:
Popup.xaml:
<Window x:Class="TryERP2.Shell.Views.Popup"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Popup" Height="315" Width="411"
xmlns:prism="http://www.codeplex.com/prism">
<Grid>
<ContentControl x:Name="DialogRegion" Grid.Row="1" prism:RegionManager.RegionName="DialogRegion" />
</Grid>
</Window>
Popup.xaml.cs:
public partial class Popup : Window
{
private static Popup popup;
private Popup(IRegionManager regionManager)
{
InitializeComponent();
RegionManager.SetRegionManager(this, regionManager);
}
//Using the singleton pattern
public static Popup getPopup(IRegionManager regionManager)
{
if (popup == null)
popup = new Popup(regionManager);
return popup;
}
}
And, finally, when I want to show the dialog (in a Command which is in a module), I just instantiate it and inform what's the RegionManager:
private void showDialog()
{
// Acquiring the RegionManager
var regionManager = ServiceLocator.Current.GetInstance<IRegionManager>();
// Getting the Popup object
Popup p = Popup.getPopup(regionManager);
// Looking for the view I want to show in the dialog
var x = new Uri("MyView", UriKind.Relative);
// Changing the view of the DialogRegion (which is within the Popup)
regionManager.RequestNavigate("DialogRegion", x);
// Showing the dialog
p.ShowDialog();
}
Related
I'm using Material Design for WPF to show a dialog which receives some inputs from the user, and I would like to return a value when it's closed. Here is the sample code:
VM's method that opens the dialog
private async void OnOpenDialog()
{
var view = new TakeInputDialogView();
var result = await DialogHost.Show(view, "RootDialog", ClosingEventHandler);
}
Dialog's VM code
public class TakeSomeInputDialogViewModel : ViewModelBase
{
private string _name;
public string Name
{
get => _name;
set
{
SetProperty(ref _name, value);
SaveCommand.RaiseCanExecuteChanged();
}
}
public bool IsNameInvalid => CanSave();
public DelegateCommand SaveCommand { get; }
public TakeSomeInputDialogViewModel()
{
SaveCommand = new DelegateCommand(OnSave, CanSave);
}
private void OnSave()
{
DialogHost.Close("RootDialog");
}
private bool CanSave()
{
return !string.IsNullOrEmpty(Name);
}
}
When the user clicks save I would like to return Name or some object that will be constructed depending on the user's input.
Side note: I'm also using Prism library, but decided to go with Material Design dialog because I can't locate the dialog in a correct place, when I open the dialog via prism I could only open it in the center of screen or in the center of owner, but I have a single window which hosts sidebar, menu control and content control, and I need to open the dialog in the middle of content control which I wasn't able to achieve.
P.S: I could bind the DataContext of the Dialog to the VM that opens it, but I might have many dialogs and the code might grow too big.
Never show a dialog from the View Model. This is not necessary and will eliminate the benefits MVVM gives you.
Rule of thumb
The MVVM dependency graph:
View ---> View Model ---> Model
Note that the dependencies are on application level. They are component dependencies and not class dependencies (although class dependencies derive from the constraints introduced by the component dependencies).
The above dependency graph translates to the following rules:
In MVVM the View Model does not know the View: the View is nonexistent.
Therefore, if the View is nonexistent for the View Model it is not aware of UI: the View Model is View agnostic.
As a consequence, the View Model has no interest in displaying dialogs. It doesn't know what a dialog is.
A "dialog" is an information exchange between two subjects, in this case the user and the application.
If the View Model is View agnostic it also has no idea of the user to have a dialog with.
The View Model doesn't show dialog controls nor does it handle their flow.
Code-behind is a compiler feature (partial class).
MVVM is a design pattern.
Because by definition a design pattern is language and compiler agnostic, it doesn't rely on or require language or compiler details.
This means a compiler feature can never violate a design pattern.
Therefore code-behind can't violate MVVM.
Since MVVM is a design pattern only design choices can violate it.
Because XAML doesn't allow to implement complex logic we will always have to come back to C# (code-behind) to implement it.
Also the most important UI design rule is to prevent the application from collecting wrong data. You do this by:
a) don't show input options that produce an invalid input in the UI. For example remove or disable the invalid items of a ComboBox, so taht the user can only select valid items.
b) use data validation and the validation feedback infrastructure of WPF: implement INotifyDataErrorInfo to let the View signal the user that his input is invalid (e.g. composition of a password) and requires correction.
c) use file picker dialogs to force the user to provide only valid paths to the application: the user can only pick what really exists in the filesystem.
Following the above principles
will eliminate the need of your application to actively interact with the user (to show dialogs) for 99% of all cases.
In a perfect application all dialogs should be input forms or OS controlled system dialogs.
ensure data integrity (which is even more important).
Example
The following complete example shows how to show dialogs without violating the MVVM design pattern.
It shows two cases
Show a user initiated dialog ("Create User")
Show an application initiated dialog (HTTP connection lost)
Because most dialogs have an "OK" and a "Cancel" button or only a "OK" button, we can easily create a single and reusable dialog.
This dialog is named OkDialog in the example and extends Window.
The example also shows how to implement a way to allow the application to actively communicate with the user, without violating the MVVM design rules.
The example achieves this by having the View Model expose related events that the View can handle. For example, the View can decide to show a dialog (e.g., a message box). In this example, the View will handle a ConnectionLost event raised by a View Model class. The View handles this event by showing a notification to the user.
Because Window is a ContentControl we make use of the ContentContrl.ContentTemplate property:
when we assign a data model to the Window.Content property and a corresponding DataTemplate to the Window.ContentTemplate property, we can create individually designed dialogs by using a single dialog type (OkDialog) as content host.
This solution is MVVM conform because View and View Model are still well separated in term of responsibilities.
Every solution is fine that follows the pattern WPF uses to display validation errors (event, exception or Binding based) or progress bars (usually Binding based).
It's important to ensure that the UI logic does not bleed into the View Model.
The View Model should never wait for a user response. Just like data validation doesn't make the View Model wait for valid input.
The example is easy to convert to support the Dependency Injection pattern.
Reusable key classes of the pattern
DialogId.cs
public enum DialogId
{
Default = 0,
CreateUserDialog,
HttpConnectionLostDialog
}
IOkDialogViewModel.cs
// Optional interface. To be implemented by a dialog view model class
interface IOkDialogViewModel : INotifyPropertyChanged
{
// The title of the dialog
string Title { get; }
// Use this to validate the current view model state/data.
// Return 'false' to disable the "Ok" button.
// This method is invoked by the OkDialog before executing the OkCommand.
bool CanExecuteOkCommand();
// Called after the dialog was successfully closed
void ExecuteOkCommand();
}
OkDialog.xaml.cs
public partial class OkDialog : Window
{
public static RoutedCommand OkCommand { get; } = new RoutedCommand("OkCommand", typeof(MainWindow));
public OkDialog(object contentViewModel)
{
InitializeComponent();
var okCommandBinding = new CommandBinding(OkDialog.OkCommand, ExecuteOkCommand, CanExecuteOkCommand);
_ = this.CommandBindings.Add(okCommandBinding);
this.DataContext = contentViewModel;
this.Content = contentViewModel;
this.DataContextChanged += OnDataContextChanged;
}
// If there is no explicit Content, use the DataContext
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) => this.Content ??= e.NewValue;
// If the content view model doesn't implement the optional IOkDialogViewModel just enable the command source.
private void CanExecuteOkCommand(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = (this.Content as IOkDialogViewModel)?.CanExecuteOkCommand() ?? true;
private void ExecuteOkCommand(object sender, ExecutedRoutedEventArgs e)
=> this.DialogResult = true;
}
OkDialog.xaml
Window Height="450" Width="800"
Title="{Binding Title}">
<Window.Template>
<ControlTemplate TargetType="Window">
<Grid>
<Grid.RowDefinitions>
<RowDefinition /> <!-- Content row (dynamic) -->
<RowDefinition Height="Auto" /> <!-- Dialog button row (static) -->
</Grid.RowDefinitions>
<!-- Dynamic content -->
<ContentPresenter Grid.Row="0" />
<StackPanel Grid.Row="1"
Orientation="Horizontal"
HorizontalAlignment="Right">
<Button Content="Ok"
IsDefault="True"
Command="{x:Static local:OkDialog.OkCommand}" />
<Button Content="Cancel"
IsCancel="True" /> <!-- Setting 'IsCancel' to 'true' will automaitcally close the dialog on click -->
</StackPanel>
</Grid>
</ControlTemplate>
</Window.Template>
</Window>
Helper classes to complete the example
MainWindow.xaml.cs
The dialog is always displayed from a component of the View.
partial class MainWindow : Window
{
// By creating a RoutedCommand, we conveniently enable every child control of this view to invoke the command.
// Based on the CommandParameter, this view will decide which dialog or dialog content to load.
public static RoutedCommand ShowDialogCommand { get; } = new RoutedCommand("ShowDialogCommand", typeof(MainWindow));
// Map dialog IDs to a view model class type
private Dictionary<DialogId, Type> DialogIdToViewModelMap { get; }
public MainWindow()
{
InitializeComponent();
var mainViewModel = new MainViewModel();
// Show a notification dialog to the user when the HTTP connection is down
mainViewModel.ConnectionLost += OnConnectionLost;
this.DataContext = new MainViewModel();
this.DialogIdToViewModelMap = new Dictionary<DialogId, Type>()
{
{ DialogId.CreateUserDialog, typeof(CreateUserViewModel) }
{ DialogId.HttpConnectionLostDialog, typeof(MainViewModel) }
};
// Register the routed command
var showDialogCommandBinding = new CommandBinding(
MainWindow.ShowDialogCommand,
ExecuteShowDialogCommand,
CanExecuteShowDialogCommand);
_ = CommandBindings.Add(showDialogCommandBinding);
}
private void CanExecuteShowDialogCommand(object sender, CanExecuteRoutedEventArgs e)
=> e.CanExecute = e.Parameter is DialogId;
private void ExecuteShowDialogCommand(object sender, ExecutedRoutedEventArgs e)
=> ShowDialog((DialogId)e.Parameter);
private void ShowDialog(DialogId parameter)
{
if (!this.DialogIdToViewModelMap.TryGetValue(parameter, out Type viewModelType)
|| !this.MainViewModel.TryGetViewModel(viewModelType, out object viewModel))
{
return;
}
var dialog = new OkDialog(viewModel);
bool isDialogClosedSuccessfully = dialog.ShowDialog().GetValueOrDefault();
if (isDialogClosedSuccessfully && viewModel is IOkDialogViewModel okDialogViewModel)
{
// Because of data bindng the collected data is already inside the view model.
// We can now notify it that the dialog has closed and the data is ready to process.
// Implementing IOkDialogViewModel is optional. At this point the view model could have already handled
// the collected data via the PropertyChanged notification or property setter.
okDialogViewModel.ExecuteOkCommand();
}
}
private void OnConnectionLost(object sender, EventArgs e)
=> ShowDialog(DialogId.HttpConnectionLostDialog);
}
MainWindow.xaml
<Window>
<Button Content="Create User"
Command="{x:Static local:MainWindow.ShowDialogCommand}"
CommandParameter="{x:Static local:DialogId.CreateUserDialog}"/>
</Window>
App.xaml
The implicit DataTemplate for the content of the OkDialog.
<ResourceDictionary>
<!-- The client area of the dialog content.
"Ok" and "Cancel" button are fixed and not part of the client area.
This enforces a homogeneous look and feel for all dialogs -->
<DataTemplate DataType="{x:Type local:CreateUserViewModel}">
<TextBox Text="{Binding UserName}" />
</DataTemplate>
<DataTemplate DataType="{x:Type local:MainViewModel}">
<TextBox Text="HTTP connection lost." />
</DataTemplate>
UserCreatedEventArgs.cs
public class UserCreatedEventArgs : EventArgs
{
public UserCreatedEventArgs(User createdUser) => this.CreatedUser = createdUser;
public User CreatedUser { get; }
}
CreateUserViewModel.cs
// Because this view model wants to be explicitly notified by the dialog when it closes,
// it implements the optional IOkDialogViewModel interface
public class CreateUserViewModel :
IOkDialogViewModel,
INotifyPropertyChanged,
INotifyDataErrorInfo
{
// UserName binds to a TextBox in the dialog's DataTemplate. (that targets CreateUserViewModel)
private string userName;
public string UserName
{
get => this.userName;
set
{
this.userName = value;
OnPropertyChanged();
}
}
public string Title => "Create User";
private DatabaseRepository Repository { get; } = new DatabaseRepository();
bool IOkDialogViewModel.CanExecuteOkCommand() => this.UserName?.StartsWith("#") ?? false;
void IOkDialogViewModel.ExecuteOkCommand()
{
var newUser = new User() { UserName = this.UserName };
// Assume that e.g. the MainViewModel observes the Repository
// and gets notified when a User was created or updated
this.Repository.SaveUser(newUser);
OnUserCreated(newUser);
}
public event EventHandler<UserCreatedEventArgs> UserCreated;
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnUserCreated(User newUser)
=> this.UserCreated?.Invoke(this, new UserCreatedEventArgs(newUser));
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
=> this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
MainViewModel.cs
class MainViewModel : INotifyPropertyChanged
{
public CreateUserViewModel CreateUserViewModel { get; }
public event EventHandler ConnectionLost;
private Dictionary<Type, object> ViewModels { get; }
private HttpService HttpService { get; } = new HttpService();
public MainViewModel()
{
this.CreateUserViewModel = new CreateUserViewModel();
// Handle the created User (optional)
this.CreateUserViewModel.UserCreated += OnUserCreated;
this.ViewModels = new Dictionary<Type, object>
{
{ typeof(CreateUserViewModel), this.CreateUserViewModel },
{ typeof(MainViewModel), this },
};
}
public bool TryGetViewModel(Type viewModelType, out object viewModel)
=> this.ViewModels.TryGetValue(viewModelType, out viewModel);
private void OnUserCreated(object? sender, UserCreatedEventArgs e)
{
User newUser = e.CreatedUser;
}
private void SendHttpRequest(Uri url)
{
this.HttpService.ConnectionTimedOut += OnConnectionTimedOut;
this.HttpService.Send(url);
this.HttpService.ConnectionTimedOut -= OnConnectionTimedOut;
}
private void OnConnectionTimedOut(object sender, EventArgs e)
=> OnConnectionLost();
private void OnConnectionLost()
=> this.ConnectionLost?.Invoke(this, EventArgs.Empt8y);
}
User.cs
class User
{
public string UserName { get; set; }
}
DatabaseRepository.cs
class DatabaseRepository
{}
HttpService.cs
class HttpService
{
public event EventHandler ConnectionTimedOut;
}
You only really need one window in a wpf application, because a window is a content control.
You can template out the entire content using an approach called viewmodel first and data templating.
That window would look like:
<Window ....
Title="{Binding Title}"
Content="{Binding}"
>
</Window>
You would then have a base window viewmodel which exposes a title property.
When you present a viewmodel to an instance of this window you'd by default just see the .ToString() of that viewmodel appear as content. To make it give you some controls you need a datatemplate.
You associate viewmodel type with control type using DataType.
Put all your markup in usercontrols. This includes your markup for mainwindow. At startup you can show an empty instance of TheOnlyWindowIneed then set datacontext asynchronously.
Then go get any data or do anything expensive you need. Once a skeleton mainwindow is up and visible. Showing a busy indicator.
Your datatemplates would all go in a resource dictionary which is merged in app.xaml.
An example
<DataTemplate DataType="{x:Type local:MyBlueViewModel}">
<local:MyBlueUserControl/>
</DataTemplate>
If you now do
var win = new TheOnlyWindowIneed { Content = new MyBlueViewModel() };
win.Owner=this;
win.ShowDialog();
Then you get a dialog shown which has the window that code is in as a parent. The datacontext is your MyBlueViewModel and your entire dialog is filled with a MyBlueUserControl.
You probably want Yes/No buttons and you probably want some standardised UI.
ConfirmationUserControl can look like:
<UserControl.....
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
<RowDefinition Height="32"/>
</Grid.RowDefinitions>
<ContentPresenter Content="{Binding ConfirmationMessage}"
Grid.Row="1"/>
<Button HorizontalAlignment="Left"
Content="Yes"
Command="{Binding YesCommand}"
/>
<Button HorizontalAlignment="Left"
Content="No"
Command="{Binding NoCommand}"
/>
</Grid>
</UserControl>
ConfirmationViewModel would expose the usual Title, ConfirmationMessage can be Another viewmodel ( and usercontrol pair ). This is then data templated out into UI in a similar fashion.
YesCommand would be a public iCommand which is set from whatever shows the dialog. This passes in whatever logic is to happen when the user clicks Yes. If it's deleting then it has code calls a delete method. It could use a lambda and capture the context of the owning viewmodel or it could have an explicit instance of a class passed in. The latter being more unit test friendly.
The call to this dialog is at the end of some code you have in your viewmodel.
There is no code waiting for the result.
The code that would be is in yescommand.
NoCommand might just close the parent window. By putting code that actions the result in yes command you probably do not need to "know" in the calling code what the user chose. It's already been handled.
You might therefore decide NoCommand uses some generic window closing approach:
public class GenericCommands
{
public static readonly ICommand CloseCommand =
new RelayCommand<Window>(o =>
{
if(o == null)
{
return;
}
if(o is Window)
{
((Window)o).Close();
}
}
);
That needs a reference to the window which is passed in by parameter
Command="{x:Static ui:GenericCommands.CloseCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}"
The viewmodel still needs to somehow initiate showing the window.
You only have the one window though. You can put code in that and initiate showing a window from the one and only window.
All you need at a minimum is a dependency property and a callback.
public partial class TheOnlyWindowIneed : Window
{
public object? ShowAdialogue
{
get
{
return (object?)GetValue(ShowAdialogueProperty);
}
set
{
SetValue(ShowAdialogueProperty, value);
}
}
public static readonly DependencyProperty ShowAdialogueProperty =
DependencyProperty.Register("ShowAdialogue",
typeof(object),
typeof(TheOnlyWindowIneed),
new FrameworkPropertyMetadata(null
, new PropertyChangedCallback(ShowAdialogueChanged)
)
);
private static void ShowAdialogueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var win = new TheOnlyWindowIneed { Content = e.NewValue };
win.Owner = d as TheOnlyWindowIneed;
win.ShowDialog();
}
Here when you bind ShowAdialogue to a property in your viewmodel, when you set that property to an instance of a dialogue viewmodel, it should show a dialog with that viewmodel as datacontext and as explained that will be templated out into UI.
A perhaps more elegant way to handle this would be to use the pub/sub pattern and the community mvvm toolkit messenger. You can send the viewmodel you want to show in a dialogue via messenger, subscribe in mainwindow and act in that handler.
If you just want to show some info then there is another option to consider. If all your users are using win10+ then you can easily use toast. The toast that pops up can have buttons in it but is usually just used to show messages.
Add the nuget package Notifications.wpf
You can show toast in your mainwindow or where notifications usually pop up in win10. In mainwindow:
<toast:NotificationArea x:Name="MainWindowNotificationsArea"
Position="BottomRight"
MaxItems="3"
Grid.Column="1"/>
In a viewmodel:
var notificationManager = new NotificationManager();
notificationManager.Show(
new NotificationContent {
Title = "Transaction Saved",
Message = $"Transaction id {TransactionId}" },
areaName: "MainWindowNotificationsArea");
The view and viewmodel are totally decoupled, you don't need any reference to anything. NotificationContent can be much richer than shown here.
I think your app might also have to target win10 as minimum O/S.
I am all confused going about implementing this in Prism. My scenario in one liner is how to achieve Prism Navigation (regionManager.RequestNavigate) in a view that is shown as a separate modal/non modal window over the main window.
Taking some code from this article, I am now able to show a separate Window, but I am very confused about navigating in the regions of the window shown. I will try to put up some code below to clarify my situation.
This code in RoomBandViewModel launches dialog
private void ManageRoomFacility() {
dialogService.ShowDialog<RoomFacilityMainWindowView>(this, container.Resolve<RoomFacilityMainWindowView>());
regionManager.RequestNavigate(RegionNames.Main_Region, new Uri("RoomFacilityMainView", UriKind.Relative));
As can be seen, I launch the Dialog which shows the View (code shown below), and then tries to navigate in One of the region of the View
The popup window RoomFacilityMainWindowView
<Window x:Class="HotelReservation.Main.View.RoomFacilities.RoomFacilityMainWindowView"
<view:RoomFacilityMainView
prism:RegionManager.RegionName="{x:Static const:RegionNames.Window_Main_Region}"/>
</Window>
UserControl within window (RoomFacilityMainView)
<UserControl x:Class="HotelReservation.Main.View.RoomFacilities.RoomFacilityMainView"
<Grid VerticalAlignment="Stretch" >
...
<Border Grid.Column="0" Style="{StaticResource RegionBorderStyle}">
<StackPanel>
<TextBlock Text="Some Sample Text"/>
<ContentControl prism:RegionManager.RegionName="{x:Static const:RegionNames.Window_List_Region}"
/>
</StackPanel>
</Border>
<GridSplitter Width="5" Grid.Column="1" HorizontalAlignment="Stretch" />
<Border Grid.Column="2" Style="{StaticResource RegionBorderStyle}" >
<TabControl x:Name="Items" Margin="5" prism:RegionManager.RegionName="{x:Static const:RegionNames.Window_Edit_Region}" />
</Border>
</Grid>
</UserControl>
Code Behind (RoomFacilityMainView.xaml.cs)
public partial class RoomFacilityMainView : UserControl {
public RoomFacilityMainView() {
InitializeComponent();
RoomFacilityMainViewModel viewModel = this.DataContext as RoomFacilityMainViewModel;
if (viewModel == null) {
viewModel = ServiceLocator.Current.GetInstance<RoomFacilityMainViewModel>();
this.DataContext = viewModel;
}
}
}
RoomFacilityMainViewModel
public class RoomFacilityMainViewModel : BindableBase {
IRegionManager regionManager;
IUnityContainer container;
public RoomFacilityMainViewModel(IRegionManager regionManager, IUnityContainer container) {
this.regionManager = regionManager;
this.container = container;
regionManager.RequestNavigate(RegionNames.Window_List_Region, new Uri("RoomFacilityListView", UriKind.Relative));
}
}
With this code no navigation occurs and I just get a blank window. The Contents of the RoomFacilityListView.xaml should be displayed, but its blank.
If the code is confusing, then please just give advice on how to navigate (use RequestNavigate) with View that has regions but shown through Dialog Service as a separate window instead of on MainWindow(Shell) .
If you're using an IDialogService implementation that shows a new window via Window.ShowDialog() method, then there's is no surprise that your navigation doesn't work. The ShowDialog() method returns only on closing the window, so your navigation request will actually be processed on a closed window, in particular after the window has closed.
There is nothing special in modal windows that would prevent using Prism regions and navigation in them. One limitation is that you cannot create multiple window instances "as is", since they all would have regions with same names, and that's not possible using one region manager. However, there is a solution: scoped region managers.
Assuming you're not going to create multiple instances, here is an example how could you solve your issue.
First, you have to ensure that your modal dialog's RegionManager is the same instance as your main RegionManager (I'm using MEF here, but actually it doesn't matter):
[Export]
public partial class Dialog : Window
{
private readonly IRegionManager rm;
[ImportingConstructor]
public Dialog(IRegionManager rm)
{
this.InitializeComponent();
this.rm = rm;
// Don't forget to set the attached property to the instance value
RegionManager.SetRegionManager(this, this.rm);
}
}
Now, extend your dialog service implementation with a method that accepts a navigation callback:
bool? ShowDialog<T>(object ownerViewModel, object viewModel, Action initialNavigationCallback = null) where T : Window
{
Window dialog = /* your instance creation code, e.g. using container */;
dialog.Owner = FindOwnerWindow(ownerViewModel);
dialog.DataContext = viewModel;
if (initialNavigationCallback != null)
{
dialog.Loaded += (s, e) => initialNavigationCallback();
}
return dialog.ShowDialog();
}
This will provide you a possibility to display a dialog with an initial navigation request, you can call it e.g. like this:
void ManageRoomFacility() {
dialogService.ShowDialog<RoomFacilityMainWindowView>(
this,
container.Resolve<RoomFacilityMainWindowView>(),
() => regionManager.RequestNavigate(
RegionNames.Main_Region,
new Uri("RoomFacilityMainView", UriKind.Relative))
);
Alternatively, you can use the state based navigation for your task. There is a sample implementation of a Send Message modal dialog in the State-Based Navigation QuickStart.
<prism:InteractionRequestTrigger SourceObject="{Binding SendMessageRequest}">
<prism:PopupWindowAction IsModal="True">
<prism:PopupWindowAction.WindowContent>
<vs:SendMessagePopupView />
</prism: PopupWindowAction.WindowContent>
</prism:PopupWindowAction>
</prism:InteractionRequestTrigger>
I'm trying to create a dialog class in WPF. This class inherits from Window and provides some default buttons and settings.
The implementation basically looks like this:
namespace Commons {
public class Dialog : Window {
public new UIElement Content {
get { return this.m_mainContent.Child; }
set { this.m_mainContent.Child = value; }
}
// The dialog's content goes into this element.
private readonly Decorator m_mainContent = new Decorator();
// Some other controls beside "m_mainContent".
private readonly StackPanel m_buttonPanel = new StackPanel();
public Dialog() {
DockPanel content = new DockPanel();
DockPanel.SetDock(this.m_buttonPanel, Dock.Bottom);
content.Children.Add(this.m_buttonPanel);
content.Children.Add(this.m_mainContent);
base.Content = content;
}
public void AddButton(Button button) {
...
}
}
}
As you can see, I redefined the Content property.
Now I want to be able to use this dialog class in XAML like this:
<my:Dialog x:Class="MyDialogTest.TestDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:Commons;assembly=Commons"
Title="Outline" Height="800" Width="800">
<!-- Dialog contents here -->
</my:Dialog>
However, this will use Window.Content when setting the dialog's contents rather than Dialog.Content. How do I make this work?
You might need to indicate a property in "your" class as being the "content property" so that the child elements described by the XAML "content" of your Dialog get put into it instead of in the "content" property of your base Window.
[ContentProperty("Content")]
public class Dialog : Window {
If that doesn't work, then try changing the name.....so try this:
[ContentProperty("DialogContent")]
public class Dialog : Window {
public new UIElement DialogContent {
get { return this.m_mainContent.Child; }
set { this.m_mainContent.Child = value; }
}
I'm new to MVVM and trying to figure out how to close a ChildWindow with the traditional Cancel button using MVVM Light Toolkit.
In my ChildWindow (StoreDetail.xaml), I have :
<Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelCommand}" />
In my ViewModel (ViewModelStoreDetail.cs), I have :
public ICommand CancelCommand { get; private set; }
public ViewModelStoreDetail()
{
CancelCommand = new RelayCommand(CancelEval);
}
private void CancelEval()
{
//Not sure if Messenger is the way to go here...
//Messenger.Default.Send<string>("ClosePostEventChildWindow", "ClosePostEventChildWindow");
}
private DelegateCommand _cancelCommand;
public ICommand CancelCommand
{
get
{
if (_cancelCommand == null)
_cancelCommand = new DelegateCommand(CloseWindow);
return _cancelCommand;
}
}
private void CloseWindow()
{
Application.Current.Windows[Application.Current.Windows.Count - 1].Close();
}
If you displayed your child window by calling ShowDialog(), then you can simply set the IsCancel property of your button control to "True".
<Button Content="Cancel" IsCancel="True" />
It becomes the same as clicking the X button on the window, or pressing ESC on the keyboard.
Have a look at this articleon MSDN. About half way down there is an approach on how to do this. Basically it uses either uses a WorkspaceViewModel or you implements an interface that exposes and event RequestClose
You then inside the Window's DataContext (if you are setting the ViewModel to it) you can attach to the event.
This is an excerpt from the article (Figure 7). You can adjust it to suit your needs.
// In App.xaml.cs
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
// Create the ViewModel to which
// the main window binds.
string path = "Data/customers.xml";
var viewModel = new MainWindowViewModel(path);
// When the ViewModel asks to be closed,
// close the window.
viewModel.RequestClose += delegate
{
window.Close();
};
// Allow all controls in the window to
// bind to the ViewModel by setting the
// DataContext, which propagates down
// the element tree.
window.DataContext = viewModel;
window.Show();
}
It's been a while since I've used WPF and MVVMLight but yes I think I'd use the messanger to send the cancel event.
In MVVM Light Toolkit the best what you can do is to use Messenger to interact with the View.
Simply register close method in the View (typically in the code behind file) and then send request to close a window when you need it.
We have implemented a NO-CODE BEHIND functionality. See if it helps.
EDIT: Here is there Stackoverflow discussion
Here are some ways to accomplish it.
Send message to your childwindow and set DialogueResult to false on childwindow code-behind.
Make property of DialogueResult and Bind it with childwindow Dialoue CLR property, set it on CancelEval method of CancelCommand.
Create object of Childwindow and set DialogueResult false on CancelEval.
Kind of late to the party but I thought I'd add my input. Borrowing from user841960's answer:
public RelayCommand CancelCommand
{
get;
private set;
}
Then:
SaveSettings = new RelayCommand(() => CloseWindow());
Then:
private void CloseWindow()
{
Application.Current.Windows[Application.Current.Windows.Count - 1].Close();
}
It's a bit cleaner than using an ICommand and works just as well.
So, to sum it all up, the example class would look like so:
public class ChildViewModel
{
public RelayCommand CancelCommand
{
get;
private set;
}
public ChildViewModel()
{
SaveSettings = new RelayCommand(() => CloseWindow());
}
private void CloseWindow()
{
Application.Current.Windows[Application.Current.Windows.Count - 1].Close();
}
}
I have a shell which looks like toolbar and defines my main region (a wrap panel). What I need to do is be able to add widgets to the shell and when a widget is clicked, a new window (view) is opened. Below is what I have so far:
I created a module class which adds a view to the main region:
public class MyModule : IModule
{
protected IUnityContainer Container { get; private set; }
public MyModule(IUnityContainer container)
{
Container = container.CreateChildContainer();
}
public void Initialize()
{
var regionManager = Container.Resolve<IRegionManager>();
MyModuleView myModuleView = new MyModuleView();
regionManager.Regions["MainRegion"].Add(myModuleView);
}
}
Here is the content of MyModuleView:
<Grid>
<Grid.DataContext>
<vm:MyModuleVM/>
</Grid.DataContext>
<Button Content="My Module" Foreground="White" FontWeight="Bold" Command="{Binding Path=LaunchCommand}">
</Button>
</Grid>
The view model, MyModuleVM:
class MyModuleVM : ObservableObject
{
protected IUnityContainer Container { get; private set; }
public MyModuleVM()
{
}
RelayCommand _launchCommand;
public ICommand LaunchCommand
{
get
{
if (_launchCommand == null)
{
_launchCommand = new RelayCommand(() => this.LaunchTestView(),
() => this.CanLaunchTestView());
}
return _launchCommand;
}
}
private void LaunchTestView()
{
TestView view = new TestView();
view.Title = "Test View";
var regionManager = Container.Resolve<IRegionManager>();
regionManager.Regions["MyWindowRegion"].Add(view);
}
private bool CanLaunchTestView()
{
return true;
}
}
So my plan was as follows:
Create the class that implements
IModule (MyModule) and have it load a
view (MyModuleView) into the shell
when initialized
Create a view model for the module
(MyModuleVM) and set it as the
DataContext of the view displayed in
the shell
MyModuleVM contains a command that a
button in MyModuleView binds to.
When the button is clicked the
command is triggered
Now, here is where I am stuck. Using
a WindowRegionAdapter (an adapter
that helps to create views in
separate windows) I wanted to create
and display a new view. As seen in
MyModuleVM, LaunchTestView needs
access to the container in order to
add the view to a region. How am I
supposed to get to the container?
Besides my specific question about accessing the container, how is my overall strategy of adding "widgets" to a toolbar shell and launching
views when they are clicked? Am I comlpetely off track here when it comes to MVVM with Prism?
Thanks guys.
You can get the container injected through constructor or property injection. To do that, the ViewModel instance must be resolved by the container, or the BuildUp method should be called after it has been instantiated.
I hope this helps.
Thanks,
Damian