zoukankan      html  css  js  c++  java
  • WPF加载XAML文件中的控件

    1.XAML文件内容,里面有一个Button控件,如下:

      <DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <Button Name="button1" Margin="100">please click me </Button>
      </DockPanel>

      

    2.界面加载这个Button的代码:

      public MainWindow()
      {

        DependencyObject  rootElement;
        using (FileStream fs = new FileStream(@"C:Users14550DesktopWindow1.xaml", FileMode.Open))
        {
          rootElement = (DependencyObject)XamlReader.Load(fs);
        }
        this.Content = rootElement;

      }

    3.XAML中的控件要使用事件时,就得去遍历XAML文件,找到对应的控件,比如上面XAML文件中的button1要使用Click事件

      public partial class MainWindow : Window
      {
        private Button btn;
        public MainWindow()
        {
          InitializeComponent();

          DependencyObject  rootElement;
          using (FileStream fs = new FileStream(@"C:Users14550DesktopWindow1.xaml", FileMode.Open))
          {
            rootElement = (DependencyObject)XamlReader.Load(fs);
          }
          this.Content = rootElement;

          btn = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "button1");
          btn.Click += btn_Click;

        }
        void btn_Click(object sender, RoutedEventArgs e)
        {
          MessageBox.Show("Hello");
        }
      }

    111
  • 相关阅读:
    C++ UNREFERENCED_PARAMETER函数的作用
    Win32 Console Application、Win32 Application、MFC三者之间的联系和区别
    解决CSDN博客插入代码出现的问题
    C++ std::vector指定位置插入
    计算机如何与人沟通(1)
    C++ fstream文件操作
    using namespace std 和 include 的区别
    找不到windows.h源文件
    C++ 字符串转换
    WPF style 换肤
  • 原文地址:https://www.cnblogs.com/zwj-199306231519/p/11141686.html
Copyright © 2011-2022 走看看