1 新建wpf程序
2 新建MyButton类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace WpfApp3
{
public class MyButton:Button
{
public Type UserWindowType { get; set; }
protected override void OnClick()
{
base.OnClick();
Window win = Activator.CreateInstance(this.UserWindowType) as Window;
if (win!=null)
{
win.ShowDialog();
}
}
}
}
3 新建窗体MyWindow
4 在主窗体中加入自定义得MyButton
<Window x:Class="WpfApp3.MainWindow"
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:WpfApp3"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<StackPanel>
<local:MyButton UserWindowType="{x:Type TypeName=local:MyWindow}" Content="click"></local:MyButton>
</StackPanel>
</Grid>
</Window>
5 点击按钮后可以弹出MyWindow窗体