在使用WPF MV-VM模式显示弹出窗口时,正确的方法是使用附加属性和消息传递。以下是一个简单的示例:
public class MainViewModel : ViewModelBase
{
private bool _isPopupVisible;
public bool IsPopupVisible
{
get { return _isPopupVisible; }
set
{
_isPopupVisible = value;
OnPropertyChanged("IsPopupVisible");
}
}
}
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<local:MainViewModel x:Key="MainViewModel" />
</Window.Resources>
<Grid>
<Button Content="Show Popup" Command="{Binding ShowPopupCommand}" />
<Popup IsOpen="{Binding IsPopupVisible, Source={StaticResource MainViewModel}}">
<StackPanel>
<TextBlock Text="This is a popup window" />
<Button Content="Close" Command="{Binding ClosePopupCommand}" />
</StackPanel>
</Popup>
</Grid>
</Window>
public class MainViewModel : ViewModelBase
{
private bool _isPopupVisible;
public bool IsPopupVisible
{
get { return _isPopupVisible; }
set
{
_isPopupVisible = value;
OnPropertyChanged("IsPopupVisible");
}
}
public ICommand ShowPopupCommand { get; private set; }
public ICommand ClosePopupCommand { get; private set; }
public MainViewModel()
{
ShowPopupCommand = new RelayCommand(() => IsPopupVisible = true);
ClosePopupCommand = new RelayCommand(() => IsPopupVisible = false);
}
}
这样,在View中点击按钮时,就可以通过命令显示或关闭弹出窗口了。
领取专属 10元无门槛券
手把手带您无忧上云