X命名空间-标记扩展

标记扩展一般含有 {} 符号

 

x:Type 传入操作数据类型

x:Null 空值


通过例子看下具体:

(前台XAML代码)

<Window x:Class="WpfApplication1.MainWindow" x:ClassModifier="public"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        xmlns:local="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <Style x:Key="{x:Type local:UCButton}" TargetType="Button">
            <Setter Property="Width" Value="80"/>
            <Setter Property="Height" Value="30" />
            <Setter Property="FontFamily" Value="Comic Sans MS" />
            <Setter Property="Foreground" Value="Blue"/>
        </Style>        
    </Window.Resources>
    <Grid>
        <local:UCButton myType="{x:Type Button}" Style="{x:Null}"  Margin="83,140,340,141" Content="Button 类型"    />
        <local:UCButton myType="{x:Type Window}"  Margin="305,140,118,141"  Content="Window 类型"   />
        <local:UCButton myType="{x:Type TextBlock}"  Margin="195,140,228,141" Content="TextBlock 类型"  />
    </Grid>
</Window>

 

(后台C#代码 ,UCButton.cs)

 

 public class UCButton:Button
    {
        public Type myType{get;set;}     //传入类型

        /// <summary>
        /// 重写点击事件
        /// </summary>
        protected override void OnClick()
        {
            base.OnClick();

            //所有控件基类,反射生成对象
            FrameworkElement element = Activator.CreateInstance(this.myType) as FrameworkElement;

            if (element != null)
            {
                MessageBox.Show(element.GetType().Name);    //显示对应类型
            }
        }
    }

 


上面用到地方有两处,

1.页面资源样式共享,目标对象UCButton,然后 Style="{x:Null}",不用于当前按钮。

2.传入类型不同,点击显示不同。

效果图:

 

x:Array 数组源对象

 <ListBox BorderBrush="AliceBlue" BorderThickness="2"  Width="80" >
            <ListBox.ItemsSource>            
                <x:Array Type="sys:String">
                    <sys:String>X</sys:String>
                    <sys:String>A</sys:String>
                    <sys:String>M</sys:String>
                    <sys:String>L</sys:String>
                </x:Array>
            </ListBox.ItemsSource>
</ListBox>

 

 

x:Static

引用静态变量

public static string WindowText = "静态变量";

  <Button  Width="80" Height="30" Content="{x:Static local:MainWindow.WindowText}"/>

 

posted @ 2012-10-02 16:57  Mr.Lin_♪  阅读(271)  评论(0)    收藏  举报