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構建后台類對象

設計器中效果如下:

運行之,效果如下:

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM