深入浅出WPF 第一部分(4)

第4章 x名称空间详解

4.2 x名称空间中的Attribute

4.2.1 x:Class

这个attribute的作用是告诉XAML编译器将XAML标签的编译结果与后台代码中指定的类合并。

  • 这个Attribute只能用于根结点,
  • 使用x:Class的根节点的类型要与x:Class的值所指示的类型保持一致。
  • x:Class的值所指示的类型在声明时必须使用partial关键字。

4.2.2 x:ClassModifier

这个Attribute的作用是告诉XAML编译由标签编译生成的类具有怎样的访问控制级别。

<Window x:Class="FirstWpfApplication.MainWindow"
        x:ClassModifier="public"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:my="clr-namespace:MyNamespace;assembly=ClassLibrary1"
        Title="Anders" Height="160" Width="296">

4.2.3 x:Name

    <StackPanel>
        <TextBox Margin="5" />
        <Button Name="button1" Margin="5" Click="button1_Click" Content="OK"/>
    </StackPanel>
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            StackPanel stackPanel = this.Content as StackPanel;
            TextBox textBox = stackPanel.Children[0] as TextBox;
            if (string.IsNullOrEmpty(textBox.Name))
                textBox.Text = "No name!";
            else
                textBox.Text = textBox.Name;
        }

4.2.4 x:FieldModifier

x:FieldModifier是用来在XAML里改变引用变量访问级别的。

        <TextBox Margin="5" x:FieldModifier="public"/>

4.2.5 x:Key

x:Key的作用就是为资源贴上用于检索的索引。在WPF中,几乎每个元素都有自己的Resources属性,这个属性是个“Key-Value”式的集合,只要把元素放进这个集合,这个元素就成为资源字典中的一个条目,当然,为了能够检索到这个条件,就必须为它添加x:Key.

    <StackPanel>
        <TextBox Name="textBox1" Margin="5" x:FieldModifier="public"/>
        <Button Name="button1" Margin="5" Click="button1_Click" Content="OK"/>
    </StackPanel>
    <Window.Resources>
        <sys:String x:Key="myStr">Hello, WPF resource!</sys:String>
    </Window.Resources>

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string str = this.FindResource("myStr") as string;
            textBox1.Text = str;
        }
4.2.6 x:Shared

一旦我们把某些对象当作资源放进资源字典里后就可以把它们检索出来重复使用。那么,每当它们检索到一个对象是我们得到的是否是一个对象时,取决于x:Shared的赋值。

x:Shared一定要与x:Key配合使用。如果x:Shared的值为true,则每次检索到的是同一对象,否则得到的是对象的新副本。默认值是true。

    <StackPanel>
        <TextBox Name="textBox1" Margin="5" x:FieldModifier="public" Text="{DynamicResource ResourceKey=myStr}"/>
    </StackPanel>
    <Window.Resources >
        <sys:String x:Key="myStr" x:Shared="true">Hello, WPF resource!</sys:String>
    </Window.Resources>




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值