動作は、このようなリサイズである:
GeneralWindow gw = new GeneralWindow(); this.Hide(); // or close gw.Show();
MVVMパターンはViewModel
からView
を分割します。したがって、新しいView
をViewModel
から作成することはできません。 。ウィンドウのインスタンスを作成し、ビューモデルからウィンドウを示すはMVVM」の違反であるだから私はあなたがContentControl
とDataTemplate
を使用してViews
を変更することができます一般的な技術を使用することをお勧めこの手法で
レッツ・ダイビング:。
<Window>
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModelA}">
<localControls:ViewAUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModelB}">
<localControls:ViewBUserControl/>
</DataTemplate>
<Window.Resources>
<ContentPresenter Content="{Binding CurrentView}"/>
</Window>
Window.DataContext
をViewModelA
のインスタンスである場合、次いでViewB
が表示され、ViewA
が表示され、Window.DataContext
はViewModelB
のインスタンスである。
私はあなたがDataTemplates
を置くべき場所、それを見ることができる例を示しましょう:
<Window x:Class="SimpleMVVMExample.ApplicationView"
...The code omitted for the brevity...
Title="Simple MVVM Example with Navigation" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type ViewModelA}">
<localControls:ViewAUserControl/>
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModelB}">
<localControls:ViewBUserControl/>
</DataTemplate>
</Window.Resources>
<DockPanel>
<Border DockPanel.Dock="Left" BorderBrush="Black" BorderThickness="0,0,1,0">
<ItemsControl ItemsSource="{Binding ListOfViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"
Command="{Binding DataContext.ChangePageCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
CommandParameter="{Binding }"
Margin="2,5"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<ContentControl Content="{Binding CurrentDataTemplateViewModel}" />
</DockPanel>
</Window>
私が今まで見たし、それはレイチェル・リムによって作られて読んだ最高の例。 See the example.
更新:
あなたが本当に新しいウィンドウが開きますをしたい場合は、あなたが新しいウィンドウを作成するための具体的な実装にViewModelには依存しないようにする中間層を作成する必要があります。
public class YourViewModel
{
private readonly IWindowFactory windowFactory;
private ICommand openNewWindow;
public YourViewModel(IWindowFactory _windowFactory)
{
windowFactory = windowFactory;
/**
* Would need to assign value to m_openNewWindow here, and
* associate the DoOpenWindow method
* to the execution of the command.
* */
openNewWindow = null;
}
public void DoOpenNewWindow()
{
windowFactory.CreateNewWindow();
}
public ICommand OpenNewWindow { get { return openNewWindow; } }
}
public interface IWindowFactory
{
void CreateNewWindow();
}
public class ProductionWindowFactory: IWindowFactory
{
#region Implementation of INewWindowFactory
public void CreateNewWindow()
{
NewWindow window = new NewWindow
{
DataContext = new NewWindowViewModel()
};
window.Show();
}
#endregion
}
ウィンドウを閉じるには?
There are a lot of approaches.。そのうちの1つは:
Application.Current.MainWindow.Close()
ビューではなくウィンドウです。 – Antoine
答えに感謝します。私は以前のウィンドウを閉じて問題を起こしていますが、どうしたらいいですか? – Antoine
@Antoine更新された回答を参照してください – StepUp