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>

  WPF加载XAML文件中的控件

2.代码:

  public MainWindow()
  {

    DependencyObject  rootElement;
    using (FileStream fs = new FileStream(@"C:\Users\14550\Desktop\Window1.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:\Users\14550\Desktop\Window1.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");
    }
  }

 

上一篇:c# – 二进制读写器同时打开?


下一篇:c# – SQLFileStream异常“找不到网络路径”