我在xaml中创建了一个弹出窗口,单击按钮时会打开该窗口。点击其他按钮我需要相同的弹出窗口。有没有一种干净的方法可以重复使用这个弹出窗口,而无需直接将其粘贴到原地?
答案 0 :(得分:2)
使用MVVM,您只需将其IsOpen
属性绑定到ViewModel,并将两个按钮都更改为true。
这是一个使用Prism的示例,但可以通过任何其他MVVM框架轻松实现:
的Xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
x:Name="mainWindow">
<Grid>
<StackPanel>
<Button Content="First Button" Command="{Binding CommandA}"/>
<Button Content="Second Button" Command="{Binding CommandB}"/>
</StackPanel>
<Popup IsOpen="{Binding IsOpen}"
AllowsTransparency="True"
Width="100"
Height="100">
<Border Background="Red">
<TextBlock Text="This is my popup"/>
</Border>
</Popup>
</Grid>
VM:
public class MainWindowViewModel : BindableBase
{
public MainWindowViewModel()
{
CommandA = new DelegateCommand(() => IsOpen = true);
CommandB = new DelegateCommand(() => IsOpen = true);
}
public DelegateCommand CommandA { get; set; }
public DelegateCommand CommandB { get; set; }
private bool isOpen;
public bool IsOpen
{
get { return isOpen; }
set
{
isOpen = value;
OnPropertyChanged(() => IsOpen);
}
}
}