"Markup extensions are used to extend the capabilities of XAML, by providing declarative
operations that need more than just setting some properties. These can be used to do pretty
much anything, so caution is advised – these extensions must preserve the declarative nature
of XAML, so that non-declarative operations are avoided; these should be handled by normal
C# code."

假如我们需要实现下面的扩展标记,这个标记扩展用来提供个随机数。

<TextBlock FontSize="{ mext:Random 10,100}" Text="DebugLZQ" x:Name="text1"/>

我们可以这样实现这个标记扩展。
1.添加一个名为CustomMarkupExtension的类库,添加一个RandomExtension.cs类,让它继承自MarkupExtension。因为MarkupExtension类在System.Xaml程序集中,因此需要添加该程序集引用。

 为实现标记扩展,我们还需要实现MarkupExtension类的ProvideValue方法。

 RandomExtension.cs如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Markup; namespace CustomMarkupExtension
{
public class RandomExtension:MarkupExtension
{
readonly int _from, _to; public RandomExtension(int from,int to)
{
_from = from;
_to = to;
} public RandomExtension(int to):this(,to)
{
} static readonly Random _rdn = new Random(); public override object ProvideValue(IServiceProvider serviceProvider)
{
return (double)_rdn.Next(_from, _to);
}
}
}

OK,完成。

2.使用这个标记扩展。我们新建一个名为TestRandom的WPF程序,添加CustomMarkupExtension类库的引用。

在需要使用的页面中,添加一个映射:

<Window x:Class="TestRandom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mext="clr-namespace:CustomMarkupExtension;assembly=CustomMarkupExtension"

注意这个映射和前面的一些映射的不同之处是:因为clr-namespace不在TestRandom程序集中,因此必须注明所在程序集名称!

这样我们就可以使用如下:

    <StackPanel>
<TextBlock FontSize="{ mext:Random 10,100}" Text="DebugLZQ" x:Name="text1"/>
<TextBlock Text="{Binding FontSize, ElementName=text1}"/>
</StackPanel>

使用方法看懂类没有?没有?关注那个构造函数。也可参考DebugLZQ的博文:WPF整理-XAML构建后台类对象

设计器中效果如下:

运行之,效果如下:

最新文章

  1. centos 7 安装mysql
  2. 封装getElementsByClassName()
  3. 分享一下学习css,js心得
  4. code::blocks 初使用遇到的问题记录
  5. &lt;!DOCTYPE html&gt;
  6. JS中的prototype属性
  7. Qt信号槽的一些事(第一次知道信号还有返回值,以及Qt::UniqueConnection)
  8. Creating Spatial Indexes(mysql 创建空间索引 The used table type doesn&#39;t support SPATIAL indexes)
  9. 你如何破解后安装PS cs6
  10. FJUTOJ-周赛2016-11-25
  11. CMS Collector and G1 Collector
  12. Kubernetes之Pod 控制器
  13. CentOS6.3上安装与配置nginx+php+mysql环境
  14. 《HTTP权威指南》2-URL
  15. php get接口,并在浏览器中以json格式返回查找到的数据
  16. 【APIO2018】铁人两项(圆方树,动态规划)
  17. XX-Net的局域网共享代理方法
  18. hystrix降级初步学习
  19. ExtJS Tab里放Grid高度自适应问题,官方Perfect方案。
  20. leetCodelinked-list-cycle-ii找到链表的环

热门文章

  1. php项目整理之no1
  2. 基于python的文件处理
  3. tornado 路由系统----扩展(include)
  4. js框架设计1.2对象扩展笔记
  5. git mac客户端使用提交与同步
  6. &lt;%#Eval if判断用法
  7. 关于网络-get/post
  8. WebConfig配置
  9. _stdcall,_cdecl区别
  10. 网络知识学习1---(基础知识:ISO/OSI七层模型和TCP/IP四层模型)