[英]WPF How to reuse Popup window xaml fragment to show on multiple different button clicks
我在xaml中創建了一個彈出窗口,單擊按鈕即可打開該窗口。 單擊其他按鈕時,我需要相同的彈出窗口。 有沒有一種干凈的方法可以重用此彈出窗口而無需將其直接粘貼到副本中?
使用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>
虛擬機:
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.