【WPF】在XAML中使用逻辑代码

1. 使用方式

<Window x:Class="InlineCodeInXaml.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="100"
        Height="80"
        mc:Ignorable="d">
    <Button Margin="5" Click="Clicked">Click Me!Button>
    <x:Code>
        
    x:Code>
Window>

【WPF】在XAML中使用逻辑代码_第1张图片

2. 注意事项

  • 代码必须被结构包含
  • 被包含的代码将被转换成当前XAML所生成分布类同级的分布类,最终与XAML分布类,后台分布类进行合并
  • 仅能使用当前XAML文件的默认XAML默认名称空间对CLR类型的映射
  • 由于不能使用using语句,需要完整限定名称
  • 由于代码被转换成分布类,因此不能定义超过分布类范畴的内容

3. 在XAML中定义变量,后台代码中使用

<Window x:Class="InlineCodeInXaml.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Title="MainWindow"
        Width="100"
        Height="80"
        mc:Ignorable="d">
    <Button Margin="5" Click="Clicked">Click Me!Button>
    <x:Code>
        
    x:Code>
Window>
using System.Windows;

namespace InlineCodeInXaml
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.abc = 123;
        }
    }
}

【WPF】在XAML中使用逻辑代码_第2张图片

你可能感兴趣的:(#,WPF,算法,wpf,c#)