WPF中UserControl的属性和事件

摘要:
WPF中有两种用户定义的控件。一个是从控件继承的用户定义控件,另一个是继承自UserControl的用户控件。用户控件可以被视为本机控件的集合。本文主要介绍如何创建用户控件及其用户定义的属性和事件。

WPF中自定义控件有两种,一种是继承自control的自定义控件,另一种是继承自UserControl的用户控件。用户控件可以认为是一系列原生控件的集合。本文主要介绍如何创建一个用户控件,以及用户控件的自定义属性和事件。

一、创建一个用户控件

1、一种是直接创建用户控件工程,这样会生成DLL,使用时调用DLL

WPF中UserControl的属性和事件第1张

2、在当前工程中直接创建

WPF中UserControl的属性和事件第2张

创建之后会生成一个xaml文件和cs文件,如下图

WPF中UserControl的属性和事件第3张

建议使用第二种方法,这样其他人在使用或修改该控件时溯源比较容易。

二、添加自定义属性

1、首先在xaml文件中添加需要的原生控件,如下:

1 <Grid>
2         <Grid.Background>
3             <ImageBrush ImageSource="pack://siteoforigin:,,,/Resources/man_bg.png"/>
4         </Grid.Background>
5         <Grid.ColumnDefinitions>
6             <ColumnDefinition/>
7             <ColumnDefinition Width="1.6*"/>
8             <ColumnDefinition/>
9         </Grid.ColumnDefinitions>
10         <Grid Grid.Column="1" >
11             <Grid.RowDefinitions>
12                 <RowDefinition/>
13                 <RowDefinition/>
14             </Grid.RowDefinitions>
15             <TextBlock x:Name="txtName" Grid.Row="0" Style="{StaticResource TextBlockStyleSmall}" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomInfoControl}},Path=CustomName}"></TextBlock>
16             <TextBox x:Name="txtCardID" Grid.Row="1" Style="{StaticResource TextBoxStyle}"  Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomInfoControl}},Path=CardID}"></TextBox>
17         </Grid>
18         <Grid Grid.Column="2">
19             <Grid.ColumnDefinitions>
20                 <ColumnDefinition Width="3*"/>
21                 <ColumnDefinition/>
22             </Grid.ColumnDefinitions>
23             <Grid.RowDefinitions>
24                 <RowDefinition/>
25                 <RowDefinition Height="3*"/>
26             </Grid.RowDefinitions>
27             <Image x:Name="imageDelete" Grid.Row="0" Grid.Column="1" 
28                    Source="pack://siteoforigin:,,,/Resources/deleteSign.png"
29                    MouseDown="btnDelete"></Image>
30             <TextBlock x:Name="txtSeatNo" Grid.Row="1" Grid.Column="0" Style="{StaticResource TextBlockStyleBig}"  Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomInfoControl}},Path=SeatNo}"></TextBlock>
31         </Grid>
32     </Grid>
View Code

此例中添加了一个两个TextBlock,一个TextBox,一个 Image.

Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type local:CustomInfoControl}},Path=CardID}"对应第二步中的依赖属性,此句一定要加,否则无法将属性值绑定到控件上。

2、在对应的后台代码中添加依赖属性

1 //定义依赖项属性
2         public static readonly DependencyProperty CustomNameProperty =
3             DependencyProperty.Register("CustomName", typeof(string), typeof(CustomInfoControl), new PropertyMetadata(""));
4         public static readonly DependencyProperty CardIDProperty =
5             DependencyProperty.Register("CardID", typeof(string), typeof(CustomInfoControl), new PropertyMetadata(""));
6         public static readonly DependencyProperty SeatNoProperty =
7             DependencyProperty.Register("SeatNo", typeof(string), typeof(CustomInfoControl), new PropertyMetadata(""));
8 
9         //声明属性        
10         /// <summary>
11         ///旅客姓名.
12         /// </summary>
13         /// <value>
14         ///The name of the custom.
15         /// </value>
16         public stringCustomName
17 {
18             get { return (string)GetValue(CustomNameProperty); }
19             set{ SetValue(CustomNameProperty, value); }
20 }
21 
22         /// <summary>
23         ///旅客卡号.
24         /// </summary>
25         /// <value>
26         ///The card identifier.
27         /// </value>
28         public stringCardID
29 {
30             get { return (string)GetValue(CardIDProperty); }
31             set{ SetValue(CardIDProperty, value); }
32 }
33 
34         /// <summary>
35         ///座位号.
36         /// </summary>
37         /// <value>
38         ///The seat no.
39         /// </value>
40         public stringSeatNo
41 {
42             get { return (string)GetValue(SeatNoProperty); }
43             set{ SetValue(SeatNoProperty, value); }
44         }
View Code

三、添加自定义事件

1、添加自定义事件DeleteInfo

1 /// <summary>
2         ///The delete event
3         /// </summary>
4         public static readonly RoutedEvent deleteEvent =
5              EventManager.RegisterRoutedEvent("DeleteInfo", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(CustomInfoControl));
6 
7         /// <summary>
8         ///删除该控件的操作.
9         /// </summary>
10         public eventRoutedEventHandler DeleteInfo
11 {
12 add
13 {
14 AddHandler(deleteEvent, value);
15 }
16 
17 remove
18 {
19 RemoveHandler(deleteEvent, value);
20 }
21         }
View Code

2、在UserControl中添加自定义事件的调用点,本例中点击叉号图片时,触发该自定义事件。

WPF中UserControl的属性和事件第4张

1 /// <summary>
2         ///点击删除按钮时的事件.
3         /// </summary>
4         /// <param name="sender">The sender.</param>
5         /// <param name="e">The <see cref="MouseButtonEventArgs"/>instance containing the event data.</param>
6         public void btnDelete(objectsender, MouseButtonEventArgs e)
7 {
8             RoutedEventArgs args = new RoutedEventArgs(deleteEvent, this);
9 RaiseEvent(args);
10         }
View Code

四、使用控件

1、使用控件时,先在xaml中添加调用。xmlns:usercontrols="clr-namespace:Client.UserControls.CustomInfoControl"

2、自定义属性使用方法如下:

<usercontrols:CustomInfoControl x:Name="customInfoControl" CustomName="张三" CardID="12345" SeatNo="12A"></usercontrols:CustomInfoControl>

或者在后台代码中添加customInfoControl.CustomName = "张三"

3、可以给自定义事件添加操作

customInfoControl.DeleteInfo += new RoutedEventHandler(DeleteCustomInfo);

 public void DeleteCustomInfo(objectsender, RoutedEventArgs e)
        {
                //TODO,请添加自定义操作
        }

至此,该控件已经可以使用。

免责声明:文章转载自《WPF中UserControl的属性和事件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇虚拟机IOS开发环境搭建教程Docker容器内无法解析DNS的问题 Could not resolve host下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

WPF之Binding

Bingding是什么 WPF中的Binding注重表达的是一种像桥梁一样的关系,它的两端分别是Binding的源(Source)和目标(Target)。数据从哪里来哪里就是源,Binding是架在中间的桥梁,Binding的目标是数据要往哪去儿。一般情况下,Binding源是逻辑层的对象,Binging的目标是UI层的控件对象。 Binding如何传递数...

WPF(MVVM) 利用资源字典实现中英文动态切换

1、首先新建两个字典文件en-us.xaml、zh-cn.xaml。定义中英文的字符串在这里面。 2、将两个资源字典添加到App.xaml中,这里注意下,因为两个字典中有同样字符,如果没有动态更改,默认后添加的生效 <ResourceDictionary Source="/Resourcedictionariesen-us.xaml"/&g...

【WPF学习】第四十九章 基本动画

  在前一章已经学习过WPF动画的第一条规则——每个动画依赖于一个依赖项属性。然而,还有另一个限制。为了实现属性的动态化(换句话说,使用基于时间的方式改变属性的值),需要有支持相应数据类型的动画类。例如,Button.Width属性使用双精度数据类型。为实现属性的动态化,需要使用DoubleAnimation类。但Button.Paddin属性使用的是Th...

WPF入门-使用C#创建简单应用

本文,你将熟悉在使用VS2019开发应用程序时可使用的许多工具、对话框和设计器。将创建一个“Hello World”应用程序、UI设计器、添加代码并调试错误。 先决条件: 安装Visual Studio 2019(16.3或者更高版本)。本文环境是16.8 一、创建项目   1、打开VS2019,   2、在‘开始’窗口,选择‘创建新项目’:      3...

WPF实现TextBox水印效果

通常情况下,在使用文本框的时候,一般会在文本框上放一段水印文字,今天用WPF来实现一下 创建一个用户控件 一般像这种常用的,最好是自己写成用户控件,防止复制粘贴大量冗余代码 XAML: <TextBox x: xmlns="http://schemas.microsoft.com/winfx/2006/xaml/prese...

WPF中RadioButton的分组

当界面上出现多组Radiobutton时,将所有的Radiobutton写在同一个Grid里面,导致系统认为所有的Radiobutton是同一组,造成选择混乱,解决的方法: 1.要为属于同个组的Radiobutton设置相同的GroupName,绑定同一个变量; 2.若没有为Radiobutton设置GroupName,则将属于同一组的Radiobutto...