使用依赖属性自定义控件,依赖属性必须定义在自定义控件中,不能定义在其他文件中

一、先实现一个类继承你要复写的类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media; namespace Demo2.Controls
{
public class UserNameBox : TextBox
{ #region 用户名图标
public string Icon
{
get { return (string)GetValue(IconProperty); }
set { SetValue(IconProperty, value); }
} // Using a DependencyProperty as the backing store for Icon. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IconProperty =
DependencyProperty.Register("Icon", typeof(string), typeof(UserNameBox));
#endregion #region 获取焦点时,用户名图标 public string Focused_Icon
{
get { return (string)GetValue(Focused_IconProperty); }
set { SetValue(Focused_IconProperty, value); }
} // Using a DependencyProperty as the backing store for Focused_Icon. This enables animation, styling, binding, etc...
public static readonly DependencyProperty Focused_IconProperty =
DependencyProperty.Register("Focused_Icon", typeof(string), typeof(UserNameBox)); #endregion #region 水印内容 public string WaterMark
{
get { return (string)GetValue(WaterMarkProperty); }
set { SetValue(WaterMarkProperty, value); }
} // Using a DependencyProperty as the backing store for WaterMark. This enables animation, styling, binding, etc...
public static readonly DependencyProperty WaterMarkProperty =
DependencyProperty.Register("WaterMark", typeof(string), typeof(UserNameBox)); #endregion #region 圆角大小 public double CornerRadius
{
get { return (double)GetValue(CornerRadiusProperty); }
set { SetValue(CornerRadiusProperty, value); }
} // Using a DependencyProperty as the backing store for CornerRadius. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register("CornerRadius", typeof(double), typeof(UserNameBox)); #endregion #region 删除按钮 public ImageBrush DeleteIcon
{
get { return (ImageBrush)GetValue(DeleteIconProperty); }
set { SetValue(DeleteIconProperty, value); }
} // Using a DependencyProperty as the backing store for DeleteIcon. This enables animation, styling, binding, etc...
public static readonly DependencyProperty DeleteIconProperty =
DependencyProperty.Register("DeleteIcon", typeof(ImageBrush), typeof(UserNameBox)); #endregion #region 是否显示密码框 public bool IsVisiblityPassword
{
get { return (bool)GetValue(IsVisiblityPasswordProperty); }
set { SetValue(IsVisiblityPasswordProperty, value); }
} // Using a DependencyProperty as the backing store for IsVisiblityPassword. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsVisiblityPasswordProperty =
DependencyProperty.Register("IsVisiblityPassword", typeof(bool), typeof(UserNameBox)); #endregion }
}

 在里面定义的依赖属性就为你自定义控件的属性,可以在布局文件中使用它们来进行设定值

可以在布局中设定值,然后在style中进行引用

<Window x:Class="Demo2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:Demo2.Controls"
xmlns:s="clr-namespace:System;assembly=mscorlib"
Background="Black"
WindowStartupLocation="CenterScreen"
Title="Demo2" Height="300" Width="300"> <Window.Resources>
<s:String x:Key="Username_Unclick">/Demo2;component/Resources/Icons/username_unclick.png</s:String>
<s:String x:Key="Username_Onclick">/Demo2;component/Resources/Icons/username_onclick.png</s:String>
<s:String x:Key="Password_Unclick">/Demo2;component/Resources/Icons/password_unclick.png</s:String>
<s:String x:Key="Password_Onclick">/Demo2;component/Resources/Icons/password_onclick.png</s:String> <ImageBrush x:Key="Delete_Icon" ImageSource="/Demo2;component/Resources/Icons/delete.png" />
</Window.Resources> <StackPanel>
<!--用户名-->
<c:UserNameBox Width="230"
Height="38"
Margin="0,20,0,0"
FontSize="18"
Text="{Binding UserName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
WaterMark="用户名"
CornerRadius="5"
DeleteIcon="{StaticResource Delete_Icon}"
Icon="{StaticResource Username_Unclick}"
IsVisiblityPassword="False"
Focused_Icon="{StaticResource Username_Onclick}"/> <!--密码-->
<c:UserNameBox x:Name="password"
Width="230"
Height="38"
Margin="0,20,0,0"
FontSize="18"
Text="{Binding Password,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
VerticalContentAlignment="Center"
WaterMark="密码"
CornerRadius="5"
IsVisiblityPassword="True"
DeleteIcon="{StaticResource Delete_Icon}"
Icon="{StaticResource Password_Unclick}"
Focused_Icon="{StaticResource Password_Onclick}"/> </StackPanel>
</Window>

  

在style中进行引用

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:c="clr-namespace:Demo2.Controls"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <Style TargetType="{x:Type c:UserNameBox}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="Background" Value="{x:Null}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type c:UserNameBox}">
<Border Background="White"
BorderThickness="0"
CornerRadius="{Binding RelativeSource={RelativeSource TemplatedParent},Path=CornerRadius}">
<Grid>
<!--分为3列-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="30"/>
<ColumnDefinition/>
<ColumnDefinition Width="40"/>
</Grid.ColumnDefinitions> <!--图标-->
<Image Grid.Column="0"
Margin="5,0,5,0"
x:Name="usernameIcon"
Source="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Icon}" /> <!--文本和水印-->
<ScrollViewer Grid.Column="1"
x:Name="PART_ContentHost"
SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
Focusable="True"/>
<TextBlock x:Name="waterMark"
Grid.Column="1"
VerticalAlignment="Center"
Foreground="Silver"
FontSize="18"
Padding="5,0,0,0" /> <!--删除按钮-->
<c:DeleteButton x:Name="deleteTextButton"
Grid.Column="2"
Width="15"
Height="15"
Style="{DynamicResource ButtonStyle2}"
ButtonBG="{Binding RelativeSource={RelativeSource TemplatedParent},Path=DeleteIcon}"
Margin="0,5,10,5"
Visibility="Visible"
VerticalAlignment="Center"
HorizontalAlignment="Right"
Focusable="False"
Command="{Binding CleanUserNameCommand}"/>
</Grid>
</Border> <ControlTemplate.Triggers>
<!--当获取焦点时-->
<Trigger Property="IsFocused" Value="true">
<Setter Property="Source" TargetName="usernameIcon" Value="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Focused_Icon}" />
</Trigger> <!--当文本为空时-->
<Trigger Property="Text" Value="">
<Setter Property="Text" TargetName="waterMark" Value="{Binding RelativeSource={RelativeSource TemplatedParent},Path=WaterMark}" />
<Setter Property="Visibility" TargetName="deleteTextButton" Value="Collapsed" />
</Trigger> <!--当属性为true时,显示密码框(将文本显示格式更改位密码显示样式)-->
<Trigger Property="IsVisiblityPassword" Value="true">
<Setter Property="Command" TargetName="deleteTextButton" Value="{Binding CleanPasswordCommand}" />
<Setter Property="Height" Value="30"/>
<Setter Property="Foreground" Value="Transparent"></Setter>
<Setter Property="FontSize" Value="20"></Setter>
<Setter Property="FontFamily" Value="Courier New"></Setter>
<Setter Property="TextDecorations">
<Setter.Value>
<TextDecorationCollection>
<TextDecoration>
<TextDecoration.Pen>
<Pen Thickness="10"
Brush="Black"
EndLineCap="Round"
StartLineCap="Round"
DashCap="Round" >
<Pen.DashStyle>
<DashStyle Dashes="0.0,1.2" Offset="0.6"/>
</Pen.DashStyle>
</Pen>
</TextDecoration.Pen>
<TextDecoration.Location>
<TextDecorationLocation>Strikethrough</TextDecorationLocation>
</TextDecoration.Location>
</TextDecoration>
</TextDecorationCollection>
</Setter.Value>
</Setter>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>

  

WPF 使用依赖属性自定义控件的更多相关文章

  1. WPF的依赖属性

    Windows Presentation Foundation (WPF) 提供了一组服务,这些服务可用于扩展公共语言运行时 (CLR)属性的功能,这些服务通常统称为 WPF 属性系统.由 WPF 属 ...

  2. wpf 的依赖属性只能在loaded 事件之后才能取到

    wpf 的依赖属性只能在loaded 事件之后才能取到,在构造函数的  InitializeComponent(); 之后取不到 wpf 的依赖属性只能在loaded 事件之后才能取到,在构造函数的  ...

  3. WPF 中依赖属性的继承(Inherits)

    WPF中依赖属性的值是是可以设置为可继承(Inherits)的,这种模式下,父节点的依赖属性会将其值传递给子节点.例如,数据绑定中经常使用的DataContextProperty: var host ...

  4. WPF 使用依赖属性(DependencyProperty) 定义用户控件中的Image Source属性

    原文:WPF 使用依赖属性(DependencyProperty) 定义用户控件中的Image Source属性 如果你要自定义一个图片按钮控件,那么如何在主窗体绑定这个控件上图片的Source呢? ...

  5. WPF的依赖属性和附加属性(用法解释较全)

    转:https://www.cnblogs.com/zhili/p/WPFDependencyProperty.html 一.引言 感觉最近都颓废了,好久没有学习写博文了,出于负罪感,今天强烈逼迫自己 ...

  6. WPF利用依赖属性和命令编写自定义控件

    以实例讲解(大部分讲解在代码中) 1,新建一个WPF项目,添加一个用户控件之后在用户控件里面添加几个控件用作测试, <UserControl x:Class="SelfControlD ...

  7. WPF: 只读依赖属性的介绍与实践

    在设计与开发 WPF 自定义控件时,我们常常为会控件添加一些依赖属性以便于绑定或动画等.事实上,除了能够添加正常的依赖属性外,我们还可以为控件添加只读依赖属性(以下统称"只读属性" ...

  8. WPF 之 依赖属性与附加属性(五)

    一.CLR 属性 ​ 程序的本质是"数据+算法",或者说用算法来处理数据以期得到输出结果.在程序中,数据表现为各种各样的变量,算法则表现为各种各样的函数(操作符是函数的简记法). ...

  9. WPF 自定义依赖属性

      原博客地址:http://www.cnblogs.com/DebugLZQ/archive/2012/11/30/2796021.html    DependencyObject和Dependen ...

随机推荐

  1. JSP和servlet之间的传值(总结的很全面)

    转自:http://blog.csdn.net/ssy_shandong/article/details/9328985 1.从一个jsp页面跳转到另一个jsp页面时的参数传递     (1)使用re ...

  2. ASP.NET Core2读写InfluxDB时序数据库

    在我们很多应用中会遇到有一种基于一系列时间的数据需要处理,通过时间的顺序可以将这些数据点连成线,再通过数据统计后可以做成多纬度的报表,也可通过机器学习来实现数据的预测告警.而时序数据库就是用于存放管理 ...

  3. MSP430 G2553 LaunchPad GPIO中断

    P1.P2端口上的每个管脚都支持外部中断.P1端口的所有管脚都对应同一个中断向量(Interrupt Vector),类似的,P2端口的所有管脚都对应另一个中断向量:通过PxIFG寄存器来判断中断来源 ...

  4. 连接池--sp_reset_connection

    --当客户端使用连接池访问数据库时,客户端使用OPEN来重用数据库连接,使用CLOSE来断开数据库连接,但并不物理上新建和断开连接,因此可以提高程序运行速度并降低性能损耗. --ADO和ADO.NET ...

  5. shell查找进程并终止

    创建kill.sh文件,内容如下: port= #一.根据端口号查询对应的pid,两种都行 pid=$(netstat -nlp | grep :$port | awk '{print $7}' | ...

  6. 开源应用框架BitAdminCore:更新日志20180605

    索引 NET Core应用框架之BitAdminCore框架应用篇系列 框架演示:http://bit.bitdao.cn 框架源码:https://github.com/chenyinxin/coo ...

  7. WP8.1StoreApp(WP8.1RT)---发送邮件和短信

    在WP7/8中,发送短信是利用了EmailComposeTask和SmsComposeTask来实现的. 在WP8.1 Store App中,原来的方式已经失效,采用了新的方法:ChatMessage ...

  8. 1、认识Redis

    Redis 是完全开源免费的,遵守BSD协议,是一个高性能的key-value数据库.Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型.Key-Value数据库, ...

  9. django系列3.1--url路由配置, 正则, 分发include, 分组命名匹配

    一.url配置 在django项目中urls.py文件中就是为这个url调用的view(视图)函数之间的映射表,来配置访问的一个url执行什么代码 默认的基本格式: from django.conf. ...

  10. P4145 上帝造题的七分钟2

    题目描述 "第一分钟,X说,要有数列,于是便给定了一个正整数数列. 第二分钟,L说,要能修改,于是便有了对一段数中每个数都开平方(下取整)的操作. 第三分钟,k说,要能查询,于是便有了求一段 ...