WPF中的x名称空间

X名称空间中的Attribute

Attribute和Property是两个层面的东西:

1)Attribute是语言层面的,是给编译器看的。

2)Property是对象层面的,是给编程逻辑用的。


x:Class

这个Attribute的作用是告诉XAML编译器将XAML标签的编译结果与后台中指定的类合并。使用X:Class时必须遵循一下要求:

1)这个Attribute只能用于根节点。

2)使用x:Class的根节点的类型要与x:Class的值所指示的类型保持一致。

3)x:Class的值所指示的类型在声明时必须使用partial关键字。



x:ClassModifier

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

需注意:

1)标签必须具有x:Class Attribute。

2)x:ClassModifier的值必须与x:Class所指示类的访问控制级别一致。

3)x:ClassModifier的值随后台代码的编译语言不通而有所不同。


x:Name

XAML的标签声明的是对象,一个XAML标签会对应着一个对象,这个对象一般是一个控制类的实例。在.NET平台上,类是应用类型。引用类型的实例在使用时一般是以“引用者——> 实例”的形式成对出现的,而且我们只能通过引用者来访问实例。当一个实例不再被任何引用者所引用时,它就会被当做内存垃圾而销毁。

常见的引用者是引用变量,但这并不是唯一的。

XAML:

<Window x:Class="Chapter4.Page33.xClassModifier.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:ClassModifier="internal"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBox Margin="5"/>
        <Button Content="OK" Margin="5" Click="Button_Click"/>
    </StackPanel>
</Window>
后台代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Chapter4.Page33.xClassModifier
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    internal partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_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;
            }
        }
    }
}

这里点击按钮的结果是“No Name”。

x:Name的作用有两个:

1)告诉XAML编译器,当一个标签带有x:Name时除了为这个标签生成对应实例外还要为这个实例声明一个引用变量,变量名就是x:Name的值。

2)将XAML标签所对应对象的Name属性&

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值