Wpf 简明教程
WPF - Custom Controls
WPF 应用程序允许创建自定义控件,这使得创建功能丰富且可定制的控件非常容易。当 Microsoft 提供的所有内置控件都不满足您的条件或您不想为第三方控件付费时,就会使用自定义控件。
WPF applications allows to create custom controls which makes it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don’t want to pay for third-party controls.
在本章中,您将学习如何创建自定义控件。在我们开始了解自定义控件之前,我们先快速了解一下用户控件。
In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let’s take a quick look at a User Control first.
User Control
用户控件提供了一种将不同的内置控件集合并打包到可重复使用的 XAML 中的方法。用户控件用于以下场景中:
User Controls provide a way to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in following scenarios −
-
If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls.
-
If the control doesn’t need support for theming. User Controls do not support complex customization, control templates, and difficult to style.
-
If a developer prefers to write controls using the code-behind model where a view and then a direct code behind for event handlers.
-
You won’t be sharing your control across applications.
Example
让我们来看一个用户控件示例,并按照以下步骤操作。
Let’s go to an example of User control and follow the steps given below.
-
Create a new WPF project and then right-click on your solution and select Add > New Item…
-
The following window will open. Now select User Control (WPF) and name it MyUserControl.
-
Click the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution.
以下是 MyUserControl.xaml 文件中使用一些属性创建按钮和文本框的 XAML 代码。
Here is the XAML code in which a button and a text box is created with some properties in MyUserControl.xaml file.
<UserControl x:Class = "WPFUserControl.MyUserControl"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable = "d" d:DesignHeight = "300" d:DesignWidth = "300">
<Grid>
<TextBox Height = "23"
HorizontalAlignment = "Left"
Margin = "80,49,0,0" Name = "txtBox"
VerticalAlignment = "Top" Width = "200" />
<Button Content = "Click Me"
Height = "23" HorizontalAlignment = "Left"
Margin = "96,88,0,0" Name = "button"
VerticalAlignment = "Top" Click = "button_Click" />
</Grid>
</UserControl>
下面给出 MyUserControl.cs 文件中按钮单击事件的 C# 代码,它更新文本框。
Given below is the C# code for button click event in MyUserControl.cs file which updates the text box.
using System;
using System.Windows;
using System.Windows.Controls;
namespace WPFUserControl {
/// <summary>
/// Interaction logic for MyUserControl.xaml
/// </summary>
public partial class MyUserControl : UserControl {
public MyUserControl() {
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e) {
txtBox.Text = "You have just clicked the button";
}
}
}
以下是 MainWindow.xaml 中添加用户控件的实现。
Here is the implementation in MainWindow.xaml to add the user control.
<Window x:Class = "XAMLUserControl.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control = "clr-namespace:WPFUserControl"
Title = "MainWindow" Height = "350" Width = "525">
<Grid>
<control:MyUserControl/>
</Grid>
</Window>
当您编译并执行上述代码时,它将生成以下窗口。
When you compile and execute the above code, it will produce the following window.
单击“单击我”按钮后,您将注意到文本框中的文本已更新。
Upon clicking the "Click Me" button, you will notice that the text inside the textbox is updated.
Custom Controls
自定义控件是一个类,它提供自己的样式和模板,这些通常在 Generic.xaml 中定义。自定义控件用于以下场景:
A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in the following scenarios −
-
If the control doesn’t exist and you have to create it from scratch.
-
If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario.
-
If your controls need to support theming and styling.
-
If you want to share your control across applications.
Example
让我们通过一个示例来了解自定义控件的工作原理。创建一个新的 WPF 项目,然后右键单击解决方案并选择添加 > 新建项…
Let’s take an example to understand how custom controls work. Create a new WPF project and then right-click on your solution and select Add > New Item…
它将打开以下窗口。现在选择 Custom Control (WPF) 并将其命名为 MyCustomControl 。
It will open the following window. Now select Custom Control (WPF) and name it MyCustomControl.
单击添加按钮,您将看到在解决方案中添加了两个新文件(Themes/Generic.xaml 和 MyCustomControl.cs)。
Click the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution.
以下是 Generic.xaml 文件中针对自定义控件设置样式的 XAML 代码。
Here is the XAML code in which style is set for the custom control in Generic.xaml file.
<ResourceDictionary
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local = "clr-namespace:WPFCustomControls">
<Style TargetType = "{x:Type local:MyCustomControl}"
BasedOn = "{StaticResource {x:Type Button}}">
<Setter Property = "Background" Value = "LightSalmon" />
<Setter Property = "Foreground" Value = "Blue"/>
</Style>
</ResourceDictionary>
以下是 MyCustomControl 类的 C# 代码,它继承自按钮类而在构造函数中重写元数据。
Here is the C# code for MyCustomControl class which is inherited from the button class and in constructor it overrides the metadata.
using System;
using System.Windows;
using System.Windows.Controls;
namespace WPFCustomControls {
public class MyCustomControl : Button {
static MyCustomControl() {
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new
FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}
}
以下是 C# 中的自定义控件单击事件实现,它将更新文本块中的文本。
Here is the custom control click event implementation in C# which updates the text of the text block.
using System;
using System.Windows;
using System.Windows.Controls;
namespace WPFCustomControls {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
}
private void customControl_Click(object sender, RoutedEventArgs e) {
txtBlock.Text = "You have just click your custom control";
}
}
}
以下是 MainWindow.xaml 中的实现,用来添加自定义控件和一个文本块。
Here is implementation in MainWindow.xaml to add the custom control and a TextBlock.
<Window x:Class = "WPFCustomControls.MainWindow"
xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:control = "clr-namespace:WPFCustomControls"
Title = "MainWindow" Height = "350" Width = "604">
<StackPanel>
<control:MyCustomControl x:Name = "customControl"
Content = "Click Me" Width = "70"
Margin = "10" Click = "customControl_Click"/>
<TextBlock Name = "txtBlock"
Width = "250" Height = "30"/>
</StackPanel>
</Window>
编译并执行上述代码后,它将生成以下窗口,该窗口带有一个自定义控件,该控件是一个自定义按钮。
When you compile and execute the above code, it will produce the following window with a custom control which is a customized button.
点击自定义按钮后,您会看到文本块中的文本被更新了。
Upon clicking the customized button, you will see that the text inside text block is updated.