使用代码和未经编译的xaml创建WPF应用程序

写xaml文件,放在对应编译后的文件夹下 windows2.xaml。

<DockPanel  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    <Button Name = "button_1" Margin="60" >"Click me"</Button>
</DockPanel>

在MainWindows.xaml 中,写带参数的构造函数。

复制代码
 public partial class MainWindow : Window
    {
        private Button mybutton;
        public MainWindow()
        {
            InitializeComponent();
        }
        public MainWindow(string xmalFile)
        {
            //设置窗体
            this.Width = this.Height = 300;
            this.Left = this.Top = 100;
            this.Title = "Dynamically Loaded XAML";

            //// 从外部文档获取XAML的内容
            //FileStream fileStream = new FileStream(xmalFile, FileMode.Open); //文件流对象, 二参打开方式

            ////用xaml文件流对象 XamlReader 加载,转换为DependencyObject对象。
            ////DependencyObject是WPF空间继承的的一个基类,可以放在任何类型的容器里。
            //DependencyObject rootElement = (DependencyObject)XamlReader.Load(fileStream);

            DependencyObject rootElement;
            //因为流的关系,使用using语句(有开有关)
            using (FileStream fileStream = new FileStream(xmalFile, FileMode.Open))
            {
                rootElement = (DependencyObject)XamlReader.Load(fileStream);
            }

            this.Content = rootElement;  //内容关联,将xaml文件显示在当前窗口
       mybutton = (Button) LogicalTreeHelper.FindLogicalNode(rootElement, "button_1");

            mybutton.Click += myButton_Click;//注册

        }
        private void myButton_Click(object sender, RoutedEventArgs e)
        {
            mybutton.Content = "Thank you.";

        }

    }
复制代码

在Program 中启动

复制代码
    class Program : Application
    {
        [STAThread()]
        static void Main()
        {
            Program app = new Program();
            app.MainWindow = new MainWindow("window2.xaml");
            app.MainWindow.ShowDialog();//采用模态方法打开。
            //模态显示(showdialog)和非模态显示(show)。
            // 模态与非模态窗体的主要区别是窗体显示的时候是否可以操作其他窗体。模态窗体不允许操作其他窗体,非模态窗体可以操作其他窗体。
        }
    }
复制代码

 

posted @   白清欢  阅读(48)  评论(0)    收藏  举报
编辑推荐:
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 如何统计不同电话号码的个数?—位图法
· C#高性能开发之类型系统:从 C# 7.0 到 C# 14 的类型系统演进全景
· 从零实现富文本编辑器#3-基于Delta的线性数据结构模型
· 记一次 .NET某旅行社酒店管理系统 卡死分析
阅读排行:
· 用c#从头写一个AI agent,实现企业内部自然语言数据统计分析
· 三维装箱问题(3D Bin Packing Problem, 3D-BPP)
· Windows上,10分钟构建一个本地知识库
· dotnet 9 通过 AppHostRelativeDotNet 指定自定义的运行时路径
· 使用 AOT 编译保护 .NET 核心逻辑,同时支持第三方扩展
点击右上角即可分享
微信分享提示