将自定义控件添加到WPF C#应用程序中
本文关键字:应用程序 WPF 自定义控件 添加 | 更新日期: 2023-09-27 17:58:14
我创建了一个示例自定义控件。它在我构建项目后生成一个dll。以下是代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace textbtn
{
public class CustomControl1 : Control
{
static CustomControl1()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
}
}
}
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:textbtn">
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<TextBlock Text="This is a Test" Foreground="Aqua" Background="AntiqueWhite"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
我正在另一个WPF应用程序中包含此dll,并希望在用户单击应用程序中的按钮时显示此自定义控件。我该怎么做?
以下是我的WPF应用程序中的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace TestCustomControls
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, RoutedEventArgs e)
{
textbtn.CustomControl1 cc = new textbtn.CustomControl1();
}
}
}
这在很大程度上取决于您所说的show。只需将其添加到显示器:
AddChild(cc);
这会将其添加到windows子组中这可能会爆炸,因为一个窗口只能有一个孩子。如果你有一个名为"ContentGrid"的根网格,那么它将是:
ContentGrid.Children.Add(cc);
这两种方法的问题都是你无法控制仓位。当然,你可以设置保证金属性等来解决这个问题。如果您的自定义控件是从Window继承的(而不是控件(,如果您想要一个对话框,您可以执行一个显示对话框:
cc.ShowDialog();
当然,比所有这些方法更好的方法是只在XAML中显示它,而不是在代码背后修改UI:(