WPF从后台动态加载控件虽然不常用到,但网上资料也不多。今天做了一个这样的小东西,记录一下:

首先,我们在在xaml文件的文件头中,加入一个动态载入的函数Loaded="Window_Loaded"

并且为window窗体命名,

 x:Name="win_mainX"

整个头部的定义如:

<Window x:Class="Listing_3.__About_Dialog_with_Tree_Walking.ImageWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ImageWindow" Height="300" Width="505" Loaded="Window_Loaded" x:Name="win_mainX">

在后台的cs文件中,我们以动态加载一个Button为例,在 Window_Loaded函数中,

如下代码:

            Canvas cContent = new Canvas();
           
            //生成一个按钮
            Button myButton = new Button();
            myButton.Content = "按钮";
            myButton.Width = 100;
            myButton.Height = 50;

           cContent.Children.Add(myButton);

           win_mainX.Content = cContent;

如果需要定义控件的位置,在xaml文件中我们看到这样<Grid></Grid>

增加一个命名如:<Grid x:Name="gdMain"></Grid>

然后,我们把win_mainX.Content = cContent;修改成

            myButton.Margin = new Thickness(10, 10, 10, 10);
            gdMain.Children.Add(cContent);

运行,一个按钮加载完成。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-11-26
猜你喜欢
  • 2021-09-03
  • 2021-08-26
  • 2022-12-23
  • 2022-12-23
  • 2021-06-22
  • 2022-12-23
相关资源
相似解决方案