![](/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.