简体   繁体   English

WPF如何重用Popup窗口xaml片段以显示多次不同的按钮单击

[英]WPF How to reuse Popup window xaml fragment to show on multiple different button clicks

I have a created a Popup window in xaml which is opened on clicking a button. 我在xaml中创建了一个弹出窗口,单击按钮即可打开该窗口。 I need the same Popup on clicking some other button. 单击其他按钮时,我需要相同的弹出窗口。 Is there a clean way to reuse this popup without copy pasting it directly inplace? 有没有一种干净的方法可以重用此弹出窗口而无需将其直接粘贴到副本中?

using MVVM you can simply bind its IsOpen property to your ViewModel and have both buttons change it to true. 使用MVVM,您可以简单地将其IsOpen属性绑定到ViewModel并使两个按钮将其更改为true。

here is an example using Prism , but can easily be implemented by any other MVVM framework: 这是使用Prism的示例,但可以通过任何其他MVVM框架轻松实现:

Xaml: 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);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM