WPF整理-自定义一个扩展标记(custom markup extension)

"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(0,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构建后台类对象

设计器中效果如下:

运行之,效果如下:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值