在WPF中,如何得到任何Object对象的XAML代码?
2021-03-26 23:24
在WPF中,可以使用System.Windows.Markup.XamlWriter.Save(objName)得到任何Object对象的XAML代码。
这里举个例子,然后来比较一下:
XAML代码:
// Window1.xaml
??? xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
??? Title="XamlWriter" Height="421" Width="485"
??? >
???
???
???
???
???
???
?
C#代码:
// Window1.xaml.cs
using System;
using System.Collections.Generic;
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.Shapes;
namespace XamlWriter
{
??? ///
??? /// Interaction logic for Window1.xaml
??? ///
??? public partial class Window1 : System.Windows.Window
??? {
??????? public Window1()
??????? {
??????????? InitializeComponent();
??????? }
??????? private void WriteXaml_A(object sender, RoutedEventArgs e)
??????? {
??????????? string savedButton = System.Windows.Markup.XamlWriter.Save(this.buttonA);
??????????? textBox1.Text = savedButton;
??????? }
??????? private void WriteXaml_B(object sender, RoutedEventArgs e)
??????? {
??????????? string savedButton = System.Windows.Markup.XamlWriter.Save(this.buttonB);
??????????? textBox1.Text = savedButton;
??????? }
??????? private void WriteGridXaml(object sender, RoutedEventArgs e)
??????? {
??????????? string savedButton = System.Windows.Markup.XamlWriter.Save(this.Grid1);
??????????? textBox1.Text = savedButton;
??????? }
??????? private void WriteCSharpCode(object sender, RoutedEventArgs e)
??????? {
??????????? Button origianlButton = new Button();
??????????? origianlButton.Height = 50;
??????????? origianlButton.Width = 100;
??????????? origianlButton.Background = Brushes.AliceBlue;
??????????? origianlButton.Content = "Click Me";
??????????? string savedButton = System.Windows.Markup.XamlWriter.Save(origianlButton);
??????????? textBox1.Text = savedButton;
??????? }
??? }
}
运行程序,当点击WriteGridXaml按钮后,我们可以看到如下结果:
为了更清晰,我将上面结果都COPY成文字,为了方便阅读,我做了适当整理(加了换行):
我们来对比一下最原始的XAML代码与我们得到的XAML代码,为了简洁,只选第一个名为“buttonA”的按钮。
原始的XAML代码(从window1.xaml中节选):
使用XamlWriter.Save()得到的XAML代码:
请注意比较,有何不同?是不是Button的属性排列次序有变?而且,Click="WriteXaml_A" 这样的代码没有了?
其他的我也不多说了,想想看为什么?
运行WriteCSharpCode(object sender, RoutedEventArgs e)后会得到些什么呢?以下是结果:
而其C#是:
Button origianlButton = new Button();
origianlButton.Height = 50;
origianlButton.Width = 100;
origianlButton.Background = Brushes.AliceBlue;
origianlButton.Content = "Click Me";
这就是C# 代码与XAML代码的相互转换了。提示:留意Background属性那句,将Brushes.AliceBlue转换成了“#FFF0F8FF”。
再想想看,这样的功能对我们有什么用途?多想多练,举一返三多得正果。
上一篇:Windows如何安装pip
文章标题:在WPF中,如何得到任何Object对象的XAML代码?
文章链接:http://soscw.com/index.php/essay/68312.html