需要用到code behind

注意要给需要访问的元素命名x:Name="PART_TextBlock"

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:CustomControlLib"> <Style TargetType="{x:Type local:MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyControl}">
<Border Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<StackPanel>
<TextBlock x:Name="PART_TextBlock" />
</StackPanel>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
custom control的程序部分

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 CustomControlLib
{ public class MyControl : Button
{
private const string TextBlockPart = "PART_TextBlock";
TextBlock textBlock;
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public override void OnApplyTemplate() //OnApplyTemplate get called everytime a template is applied to the control,control update
{
base.OnApplyTemplate(); //Button有自己的OnApplyTemplate我们需要call这个beofre call我们自己写的OnApplyTemplate方法
if (textBlock != null) //避免memory leak每次call OnApplyTemplate方法时都给同一个textBlock加上event
{
textBlock.TextInput -= new TextCompositionEventHandler(textBlock_TextInput);
} textBlock = GetTemplateChild(TextBlockPart) as TextBlock;
if (textBlock != null)
{
textBlock.Text = "Set from code";
textBlock.TextInput +=new TextCompositionEventHandler(textBlock_TextInput);
} } private void textBlock_TextInput(object sender, TextCompositionEventArgs e)
{ }
}
}
使用该control
<Window x:Class="CustomControlDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cc="clr-namespace:CustomControlLib;assembly=CustomControlLib"
Title="MainWindow"
Width="525"
Height="350">
<Grid>
<cc:MyControl />
</Grid>
</Window>

改进:上面的方法不好,设想如果controlTemaplte里有很多element都需要访问,每一个元素都需要后台程序这样访问的话,会很乱

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 CustomControlLib
{
[TemplatePart(Name = TextBlockPart, Type = typeof(TextBlock))] //告诉使用template的作者这里x:Name为PART_TextBlock的control一定要是TextBlock类型的
public class MyControl : Button
{
private const string TextBlockPart = "PART_TextBlock";
TextBlock _textBlock; //避免每一次call OnApplyTemplate都在方法体里创建一个TextBlock,在方法前定义一个变量来储存
protected TextBlock TextBlock
{
get {return _textBlock; }
set
{
if (_textBlock != null) //避免memory leak每次call OnApplyTemplate方法时都给同一个textBlock加上event
{
_textBlock.TextInput -= new TextCompositionEventHandler(textBlock_TextInput);
} _textBlock = value; if (_textBlock != null)
{
_textBlock.Text = "Set from code";
_textBlock.TextInput += new TextCompositionEventHandler(textBlock_TextInput);
}
}
}
static MyControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyControl), new FrameworkPropertyMetadata(typeof(MyControl)));
}
public override void OnApplyTemplate() //OnApplyTemplate get called everytime a template is applied to the control,control update
{
base.OnApplyTemplate(); //Button有自己的OnApplyTemplate我们需要call这个beofre call我们自己写的OnApplyTemplate方法 TextBlock = GetTemplateChild(TextBlockPart) as TextBlock; //每次call都赋值属性
} private void textBlock_TextInput(object sender, TextCompositionEventArgs e)
{ }
}
}

TemplatePart(Name="PART_Decrease", Type=typeof(RepeatButton))

一直没明白这是干嘛用的,搜了一下,记载一下。

以Button的定义为例:

namespace System.Windows.Controls
{
// Summary:
// Represents a button control, which reacts to the Click event.
[TemplatePart(Name = "Normal State", Type = typeof(Storyboard))]
[TemplatePart(Name = "MouseOver State", Type = typeof(Storyboard))]
[TemplatePart(Name = "RootElement", Type = typeof(FrameworkElement))]
[TemplatePart(Name = "Pressed State", Type = typeof(Storyboard))]
[TemplatePart(Name = "FocusVisualElement", Type = typeof(UIElement))]
[TemplatePart(Name = "Disabled State", Type = typeof(Storyboard))]
public class Button : ButtonBase
{
// Summary:
// Initializes a new instance of the Button class.
public Button();
// Summary:
// Apply a template to the Button.
protected override void OnApplyTemplate();
//
// Summary:
// Called when the IsEnabled property changes.
//
// Parameters:
// isEnabled:
// New value of the IsEnabled property.
protected override void OnIsEnabledChanged(bool isEnabled);
}
}

[TemplatePart(Name = "Normal State", Type = typeof(Storyboard))] 这种东东是做什么用的 , 其实这是一种契约 , 是一种推荐的控件设计模式(只是推荐) , 意思是告诉要来写ControlTemplate的用户 , 你的ControlTemplate中需要有一个x:Name为“Normal State” , 类型为Storyboard , 当然这个类型可以是继承来的, 为什么一定要包含这些契约规定的元素 , 因为逻辑部分对这些东西进行了引用,它们将对控件的默认行为起着关键作用, 可以理解为这个控件的最基本元素 , 是实现默认行为的最小集合, 自然,你的ControlTemplate中如果没有包含契约中的内容 , 则相应的逻辑将无法实现。

所以说白了,就是提示用的.....这么写比较规范。

访问ControlTemplate内部的元素的更多相关文章

  1. Div 内部所有元素 全部垂直对齐

    http://stackoverflow.com/questions/7273338/how-to-vertically-align-an-image-inside-div How it works: ...

  2. C++ multimap容器访问同一键值元素的不同方法

    multimap是一种多元map容器,允许一个键对应多个值. 本文介绍了 multimap访问同一键值元素的三种不同方法,详细看下面代码: typedef multimap<string,int ...

  3. WPF如何得到一个在用户控件内部的元素的坐标位置

    例如有这样一个用户控件: <UserControl d:DesignHeight="100" d:DesignWidth="200" ...> &l ...

  4. Arduino内部网页代理,网页穿透,公网访问Arduino内部网页

    #include <ESP8266WiFi.h> const char* id     = "id";  //http://www.mcunode.com/proxy/ ...

  5. 访问树中的所有元素(DOM)

    创建一个函数,给定页面上的DOM元素,将访问元素本身及其所有后代(而不仅仅是它的直接子代).对于访问的每个元素,函数应将该元素传递给提供的回调函数. 函数的参数应该是: 一个DOM元素 一个回调函数( ...

  6. vue学习(五) 访问vue内部元素或者方法

    //html <div id="app"> <input type="button" value="ok" v-bind: ...

  7. Windows Store App 访问应用内部文件

    访问应用程序内部的文件可以使用多种不同的方法,13.1节中已经介绍过相关的方法,除此之外,还可以使用文件的URI地址直接对文件进行检索,这种访问方式需要用到StorageFile类的静态方法GetFi ...

  8. 兼容性背景颜色半透明CSS代码(不影响内部子元素)

    如何简单兼容性的实现父元素是半透明背景色,而子元素不受影响. 兼容所有浏览器的背景颜色半透明CSS代码: background-color: rgba(, , , .); filter: progid ...

  9. internet访问局域网内部方法之----------路由器端口映射

    很多人每天都问为什么要端口映射?例如:通过路由器上网的,网站自己可以访问,但是别人就不能:输入127.0.0.1可以访问,别人还是看不到:输入localhost可以看到,但是别人就是看不到,气人啊-没 ...

随机推荐

  1. 支持向量机之Hinge Loss 解释

    Hinge Loss 解释 SVM 求解使通过建立二次规划原始问题,引入拉格朗日乘子法,然后转换成对偶的形式去求解,这是一种理论非常充实的解法.这里换一种角度来思考,在机器学习领域,一般的做法是经验风 ...

  2. NHibernate实例化类部分属性

    NHibernate 为习惯SQL的开发者提供了接口,将查询的结果转变为持久化对象.虽然该方法不是很提倡. GetCurrentSession().CreateSQLQuery(sql) 参数sql就 ...

  3. SPY++的使用

    百度百科Spy++ 使用的是VS2010.net自带的功能,可以从开始菜单中打开.

  4. testng之listener

    这周在给人培训selenium+testng框架时,讲到listener这块发现对listener并没有完全了解,于是自己又重新学习了下. 以下是 TestNG 提供的几种监听器: IAnnotati ...

  5. LR 解决中文乱码(来源——百度)

    因为我们使用的中文操作系统默认的中文编码格式是GB2312,所以LR对服务器的返回内容自动使用GB2312方式阅读的,但是几乎所有的中文网站现在都在使用UTF-8的方式来编码,由于解码编码的方式不同最 ...

  6. Chapter14:重载运算符

    对于一个运算符函数来说,它或者是类的成员,或者至少含有一个类类型的参数. int operator+(int, int);//错误,不能为int重定义内置运算符 对于一个重载的运算符来说,其优先级和结 ...

  7. C++11 多线程

    C++11开始支持多线程编程,之前多线程编程都需要系统的支持,在不同的系统下创建线程需要不同的API如pthread_create(),Createthread(),beginthread()等,使用 ...

  8. 【转】SQL Server 数据库内部版本号

    -----------数据库还原或版本升级出现版本错误时可参考. Internal SQL Server Database Version Numbers A database created by ...

  9. WinForm 根据屏幕分辨率自适应

    方法来自百度, 不算太好,但目前能满足需求.(窗口在LOAD的时候记录每个控件的坐标,每次窗口重绘的时候引时SizeChange事件,根据比率重新设置坐标) 以下是代码  AutoSizeFormCl ...

  10. 图解WPF程序打包全过程

    首先打开已经完成的工程,如图: 下面开始制作安装程序包. 第一步:[文件]——[新建]——[项目]——安装项目. 名称——可以自己根据要求修改. 位置——是指你要制作的安装文件存放在什么目录内,可以根 ...