gpt4 book ai didi

wpf - 使用MVVM在wpf中的父窗口中打开子窗口

转载 作者:行者123 更新时间:2023-12-03 10:55:40 26 4
gpt4 key购买 nike

我有一个名为“DashBoard”的窗口。用户成功登录后,将显示此窗口。现在,当用户从菜单项中选择一个选项时,我想在仪表板内打开一个名为“成员列表”的子窗口。用户不应从“仪表盘”窗口中拉出“成员列表”窗口。

DashboardView.xmal(父窗口)

<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>

MemberlistView.xaml(子窗口)
<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>

DashboardViewModel.cs
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中引用 View 。而是创建一个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>

只要 CurrentViewnull,该控件就永远不可见。一旦执行了显示 MemberView的命令, CurrentView就会设置为 MemberViewModel,并且ContentControl将被填充

关于wpf - 使用MVVM在wpf中的父窗口中打开子窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7446825/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com