WPF MarkupExtension

MarkupExtension 标记扩展。wpf中已实现了很多MarkupExtension。如binding,x:StaticResource等等。通过继承MarkupExtension,我们可以自定义标记。

 public class ColorExtend : MarkupExtension
    {
        string _flag;
        public ColorExtend(string flag)
        {
            _flag = flag;
        }
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            switch(_flag)
            {
                case "G":
                    return Brushes.Green;
                case "R":
                    return Brushes.Red;
                default:
                    return Brushes.Black;

            }
        }
    }

再ProvideValue中,根据xaml中传入的参数,返回转换后的对象。比如,我xaml中传入字符"G",通过自定义标记扩展,可以返回颜色Green对象。

xmal中使用:

<Window x:Class="MarkupExtensionTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MarkupExtensionTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBlock Text="test111111" Foreground="{local:ColorExtend G}"  />
        <TextBlock Text="test111111" Foreground="{local:ColorExtend R}" Margin="10,106,625.6,257"  />
        <TextBlock Text="test111111" Foreground="{local:ColorExtend 111}" Margin="10,62,635.6,314"  />
    </Grid>
</Window>

效果图:

 

posted @ 2020-04-22 15:57  liuyong111  阅读(525)  评论(0编辑  收藏  举报