WPF 读取xaml文档

2017-06-05 11:34:44来源:CSDN作者:qq_21489689人点击

    /// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        private Button myButton;        public MainWindow()        {            InitializeComponent();        }        public MainWindow(string xamlFile)//重写MainWindow,并传递一个参数(xmal路径)        {            this.Width = this.Height = 285;            this.Top = this.Left = 100;            this.Title = "Dynamically Loaded XAML.";            //从一个XAML文件里获取XAML内容            DependencyObject rootElement;//定义依赖对象            using (FileStream fs = new FileStream(xamlFile, FileMode.Open))            {                rootElement = (DependencyObject)XamlReader.Load(fs);//将读到的xaml内容赋值给rootElement            }            this.Content = rootElement;            myButton = (Button)LogicalTreeHelper.FindLogicalNode(rootElement, "button1");//利用LogicalTreeHelper.FindLogicalNode(rootElement, "button1")从rootElement中找到button1            myButton.Click+=myButton_Click;        }        private void myButton_Click(object sender, RoutedEventArgs e)//button点击事件        {            myButton.Content = "Thank you.";        }    }
    //重新定义启动程序,将原来的app.cs删除
    class Program:Application    {        [STAThread]        static void Main()        {            Program app = new Program();            app.MainWindow = new MainWindow("Window1.xaml");//将window1.xaml放到debug目录下,可以直接读取            app.MainWindow.ShowDialog();        }    }
    //window1中的内容
    <DockPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">    <Button Name="button1" Margin="60">Please click me.</Button>    </DockPanel>

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台