1. 程式人生 > >X名稱空間的特性(Attribute)x:key和x:type

X名稱空間的特性(Attribute)x:key和x:type

x名稱空間指向http://schemas.microsoft.com/winfx/2006/xaml.它包含的類與xaml有關.

大致有以下一些: attribute: X:class          告訴XAML編譯器將XAML標籤的編譯結果與後臺的哪個類合併 x:classmodifier            生成的類的訪問級別 與x:class 指定的類的控制級別必須相同 x:fieldmodifier          是用來改變引用變數訪問級別的             x:key                            把東西存放到資源字典Resource Dictionary裡的Key,檢索時用這個Key
x:name                     XAML標籤對應物件的Name屬性也設為x:Name的值,並把這個值註冊到UI樹上,方便查詢 x:type                     擴充套件標記,資料的型別 一個x:key和x:type的demo;
public class myButton : Button
    {
        public Type UserWindowType { set; get; }            //自定義的屬性
        protected override void OnClick()
        {
             base.OnClick();
                Window win = Activator.CreateInstance(UserWindowType) as Window;
                if (win != null)
                {
                    win.ShowDialog();
                }
            }
            }
         
    }
自定義一個button,增加一個屬性為type型別 重寫點選事件,建立一個物件以我們定義的型別,並強制轉為window 佈局:
<Window x:Class="x名稱空間.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:x名稱空間"
        mc:Ignorable="d"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <local:myButton UserWindowType="{x:Type TypeName=local:Window1}" Margin="5">Show</local:myButton>
    </StackPanel>
</Window>


新增local名稱空間匯入本地的程式集 建立了自定義的button ,屬性使用x名稱空間的擴充套件標記x:type。為本地的window1,所以建立一個window1的視窗 點選解決方案中的新增,新增視窗window1, 佈局:
<Window x:Class="x名稱空間.Window1"
        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:x名稱空間"
        mc:Ignorable="d"
        Title="Window1" Height="300" Width="300"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        >
    <Window.Resources>
        <sys:String x:Key="str">Hello</sys:String>
    </Window.Resources>
    <StackPanel>
        <TextBlock Margin="5" Text="{StaticResource str}"></TextBlock>
        <TextBlock x:Name="text1" Margin="5"></TextBlock>
        <Button Margin="5" Click="Button_Click">Show</Button>
    </StackPanel>
</Window>
資源中使用x:key定義了一個值; 在textblock中使用了定義的值 button的事件處理函式
 private void Button_Click(object sender, RoutedEventArgs e)
        {
            text1.Text = (string)FindResource("str");
  
        }
使用findResource根據關鍵字找到定義的值。 實際執行效果: