Answer the question
In order to leave comments, you need to log in
How to work with windows in WPF/MVVM?
Hello.
How to properly implement windows in WPF/MVVM? For example, the main form for entering login / passwords opens, after entering data, another form opens, depending on which user and what role he has. I googled and didn't find any suitable examples. Everywhere modal windows are considered. Leave examples, please. Which are made strictly in accordance with the MVVM pattern. Thanks to.
Answer the question
In order to leave comments, you need to log in
Good afternoon.
Here is an old article with three different implementations of showing child windows. Now I'm actually using a different approach. When all child Views are created as controls. The child window is one and contains a ContentPresenter. When a child window's show method is called, a ViewModel is placed in its DataContext. And how to match View and ViewModel stored in resources:
<DataTemplate DataType="{x:Type viewmodel:ResponsePart8ViewModel}">
<view:ResponsePart8View HorizontalAlignment="Stretch" />
</DataTemplate>
there are no navigation conventions in the MVVM pattern. The
topic itself is complex, I recommend to see how it
is
done in
Prism which shows the necessary View according to the transferred VM, stores the backstack, etc.
I don't see a problem, to be honest. If the view model is initialized in all windows in the same way, especially if automatically, then you can simply create windows and show them. Different depending on the conditions.
Example:
Model:
namespace MyApp.MyNamespace.ViewModels
{
public class MyWindowModel : INotifyPropertyChanged
{
private object _foo;
public object Foo
{
get { return _foo; }
set { _foo = value; RaisePropertyChanged("Foo"); }
}
...
}
}
<Window x:Class="MyApp.MyNamespace.MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:viewModels="clr-namespace:MyApp.MyNamespace.ViewModels">
<Window.DataContext>
<viewModels:MyWindowModel x:Key="Model" />
</Window.DataContext>
<Grid>
<TextBlock Text={Binding Foo} />
</Grid>
</Window>
...
// проверяем успешность логина
if (!loginSuccess)
return;
// если всё хорошо, то создаём новое окно
var myWindow = new MyWindow();
// если нужно - что-то делаем с моделью внутри окна
var model = myWindow.DataContext as MyWindowModel;
model.Foo = new object();
// показываем новое окно
myWindow.Show();
// закрываем текущее окно логина
var window = Application.Current.Windows[0];
if (window != null)
window.Close();
So it's not difficult.
On the button you hang a command with logic and a transition to the desired page.
I can throw off the simplest example with Prism, but for UWP.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question