![](/img/trans.png)
[英]Issue with opening Child window from Main window using WPF with MVVM
[英]open child window inside a parent window in wpf using MVVM
我有一个名为“ DashBoard”的窗口。 用户成功登录后,将显示此窗口。现在,当用户从菜单项中选择一个选项时,我想在仪表板内打开一个名为“成员列表”的子窗口。 用户不应从“仪表盘”窗口中拉出“成员列表”窗口。
<Window x:Class="MyProject.DashboardView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="My Project: Dashboard" Height="600" Width="800" WindowState="Maximized"
WindowStartupLocation="CenterOwner">
<Grid>
<Menu Height="23" HorizontalAlignment="Left" Name="menu1" VerticalAlignment="Top"
Width="44">
<MenuItem Header="_File" >
<MenuItem Header="View Memberlist…" Command="{Binding
Path=DisplayMemberlistCommand}" />
</MenuItem>
</Menu>
</Grid>
</Window>
<Window x:Class="MyProject.MemberlistView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="View Memberlist" Height="400" Width="806">
<Grid>
<Grid Height="383" Width="1179">
<toolkit:DataGrid x:Name="dgMemberlist"
ItemsSource="{Binding Path=MemberList}"
AutoGenerateColumns="False" Margin="21,57,422,106"
SelectedItem="{Binding Path=SelectedMemberItem,
UpdateSourceTrigger=PropertyChanged}">
<toolkit:DataGrid.Columns>
<toolkit:DataGridTextColumn Header="Export ID" Width="100"
Binding="{Binding MemberfullName}" IsReadOnly="True" />
</toolkit:DataGrid.Columns>
</toolkit:DataGrid>
</Grid>
</Grid>
</Window>
private ICommand _displayMemberlistCommand;
public ICommand DisplayMemberlistCommand
{
get
{
if (_displayMemberlistCommand == null)
_displayMemberlistCommand = new RelayCommand(a=>DoDisplayMemberlist(),
p=>true);
return _displayMemberlistCommand;
}
set
{
_displayMemberlistCommand = value;
}
}
private void DoDisplayMemberlist()
{
DashboardView dv = new DashboardView();
MemberlistView mlWindow = new MemberlistView ();
mlWindow.Owner = Application.Current.MainWindow;
mlWindow .Show();
}
我建议不要在ViewModel中引用视图。 而是创建一个MemberListViewModel
,并使用DataTemplate
进行显示。
因此,您的DashBoardViewModel
将有一个
ViewModelBase CurrentView {get; set;}
属性,并在ShowMemberListCommand
简单地设置
CurrentView = new MemberListViewModel();
您的DashboardView
将包含
<ContentControl Content="{Binding CurrentView}">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type local:MemberViewModel}">
<local:MemberView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
只要CurrentView
为null
,该控件就永远不可见。 一旦执行了显示MemberView
的命令, CurrentView
将被设置为MemberViewModel
,并且ContentControl将被填充
由于我不知道专业术语,因此我花了更长的时间找到解决方案。 我正在审阅MDI(多文档界面)。 我在此URL http://wpfmdi.codeplex.com/上找到了非常好的示例代码示例
使MemberListView成为UserControl而不是Window,然后单击菜单将其添加到主窗口内容中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.