65.9K
CodeProject 正在变化。 阅读更多。
Home

如何在 XAML 文件中嵌入 C# 代码

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.89/5 (25投票s)

2009年10月10日

CPOL

3分钟阅读

viewsIcon

85509

downloadIcon

1417

关于如何在 XAML 文件中嵌入 C# 代码的简单教程。

引言

这是一个关于如何在 XAML 文件中嵌入 C# 代码的简单教程。

基于 Windows 的 WPF 应用程序需要以非常特殊的方式响应用户界面事件。这就是 XAML 必须由真正的编程代码补充的地方。您可以将代码放在 CS 的单独文件中,也可以直接将其嵌入到 XAML 中。在本文中,为了简单起见,我将展示后一种方法。对于您来说,完全有可能将 C# 代码嵌入到 XAML 文件中。它并不美观,但它有效。 XAML 实际上支持“内部代码”,而不是代码隐藏(有点像 ASP.NET)。如果你不想使用 CS 文件(我不知道为什么),这种方式会有帮助。

这可以通过 XAML 语言命名空间中的 Code 关键字来完成,如下所述。

Using the Code

第一步是在 Visual C# 中创建 WPF 应用程序项目并删除 C# 源代码,即匹配指定 CS 扩展名的文件。

Sample Image - maximum width is 600 pixels

起始点是一个 XAML 模板,默认名为 App.xaml。您不需要更改此文件的数据。

<Application x:Class="WpfApplicationWithoutCShFiles.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
    <Application.Resources>

    </Application.Resources>
</Application>

注意Class 属性用于 XAML 中,以创建派生自该元素的类。 Visual Studio 从 Application 类派生一个自定义类,名为 WpfApplicationWithoutCShFilesWpfApplicationWithoutCShFiles 是项目的名称,它与定义类的命名空间相同,而 App 是 Visual Studio 用于派生自 Application 的自定义类的名称。 App.xaml 文件必须具有 ApplicationDefinition 的 Build Action,否则将不起作用。 如果你愿意,你可以将类名更改为更令人兴奋的名称。)

Application 标记不仅创建了一个自定义应用程序类,还设置了 StartupUri 属性,以标识代表主窗口的 XAML 文档。 请注意,StartupUriWindow1.xaml 文件,就是这一个

<Window x:Class="WpfApplicationWithoutCShFiles.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF Application Without CSharp Files"
    SizeToContent="WidthAndHeight"
    ResizeMode="CanMinimize"
    Height="300" Width="1000">

    <Grid Height="255" Width="930">

        <Button Margin="400,67,404,126"
                Click="ButtonOnClick">
            Press the Button
        </Button>

        <x:Code>
            <![CDATA[

            void ButtonOnClick(object sender, RoutedEventArgs args)
            {
                Button btn = sender as Button;
                MessageBox.Show("The button labeled '" +
                                btn.Content +
                                "' has been clicked.","Information Message");
            }
            ]]>
        </x:Code>
    </Grid>
</Window>

嵌入代码需要使用 x:Code 元素和 CDATA 部分,位于 x:Code 元素内。 XML 规范将 CDATA(代表“字符数据”)定义为 XML 文件中“包含字符的文本块,这些字符否则将被识别为标记”,这对于 C# 和其他编程语言中使用的符号来说当然是这样。

CDATA 部分总是以字符串 "<![CDATA[" 开头,并始终以字符串 "]]>" 结尾。<![CDATA[ ]]> 标签用于告诉 XML 解析器忽略其中包含的任何内容。 没有它,某些 C# 代码可能会使 XML 解析崩溃。你必须避免在代码中的任何地方使用 ]]>,因为它会终止 CDATA 部分!
例如,以下示例可能会导致上述问题

m_Data = (arr_one[arr_two[3]]> 100) ? arr_one[arr_two[3]] : 0 ;

您可以通过在那个无意的 CDATA 分隔符内的某处插入一点空格来解决这个问题,一切都会好起来的。
此嵌入代码不能定义字段。 如果生成的代码文件未自动包含这些命名空间的 using 指令,则 C# 代码可以要求完全限定的命名空间名称。 考虑到文件 Window1.xaml 中的嵌入代码应完全限定 System.Reflection 命名空间中的类。

编译此类 XAML 文件时,x:Code 元素中的内容会被放置到 Window1.g.cs 文件中的部分类中(后缀为 .g.cs 的 C# 源文件,其中 g 代表生成的。代码确实会在 XAML 编译过程中生成,但这只是一些“胶水代码”,类似于必须编写的内容,才能在运行时加载和解析松散的 XAML 文件)。

using System;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplicationWithoutCShFiles {

    /// <summary>
    /// Window1
    /// </summary>
    public partial class Window1 : System.Windows.Window, 
		System.Windows.Markup.IComponentConnector {

        private bool _contentLoaded;

        #line 17 "..\..\Window1.xaml"

            void ButtonOnClick(object sender, RoutedEventArgs args)
            {
                Button btn = sender as Button;
                MessageBox.Show("The button labeled '" +
                                btn.Content +
                                "' has been clicked.","Information Message");
            }

        #line default
        #line hidden

        /// <summary>
        /// InitializeComponent
        /// </summary>
        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent() {
            if (_contentLoaded) {
                return;
            }
            _contentLoaded = true;
            System.Uri resourceLocater = new System.Uri("/WpfApplicationWithoutCShFiles;
			component/window1.xaml", System.UriKind.Relative);

            #line 1 "..\..\Window1.xaml"
            System.Windows.Application.LoadComponent(this, resourceLocater);

            #line default
            #line hidden
        }

        [System.Diagnostics.DebuggerNonUserCodeAttribute()]
        [System.ComponentModel.EditorBrowsableAttribute
		(System.ComponentModel.EditorBrowsableState.Never)]
        [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute
	    ("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
        void System.Windows.Markup.IComponentConnector.Connect
				(int connectionId, object target) {
            switch (connectionId)
            {
            case 1:

            #line 12 "..\..\Window1.xaml"
            ((System.Windows.Controls.Button)(target)).Click += 
		    new System.Windows.RoutedEventHandler(this.ButtonOnClick);

            #line default
            #line hidden
            return;
            }
            this._contentLoaded = true;
        }
    }
}

尽管在 XAML 文件中嵌入 C# 代码有时很方便,但给定的技术不应经常使用,因为它不如通用解决方案优雅。 除了使 UI 和逻辑之间的划分变得混乱之外,松散的 XAML 页面不支持它,并且 Visual Studio 不会显示语法着色。

历史

  • 08/04/09:初始问题
© . All rights reserved.