C#/WPF

런타임중에 XAML 로드하기 (Loading XAML at runtime)

sheepone 2021. 12. 15. 15:41
반응형

런타임중에 XAML파일을 읽어와 해당 UI를 원하는 곳에 적용

 

1.MainWindow

MainWindow.xaml

<Window x:Class="WpfApp8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp8"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Name="GridMain">
        
    </Grid>
</Window>

Grid 하나에 이름을 넣어줍니다.

 

MainWindow.xaml.cs

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            string directory = System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString();
            directory = System.IO.Directory.GetParent(directory).ToString();

            //Add UserControl
            StreamReader sr = new StreamReader(directory + "\\UserControl1.xaml");
            FrameworkElement userContent = XamlReader.Load(sr.BaseStream) as FrameworkElement;

            //Add Button Event
            var Button1 = LogicalTreeHelper.FindLogicalNode(userContent, "Button1") as Button;
            Button1.Click += new RoutedEventHandler(Button_Click1); 

            GridMain.Children.Add(userContent);

        }
        private void Button_Click1(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Added At Runtime");
        }

    }

Usercontrol1.xaml을 읽어와서 그리드메인에 연결합니다.

버튼은 이름으로 찾아와 해당 버튼에 이벤트를 연결해 줍니다.

 

2. UserControl

UserControl1.xaml

<UserControl 
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApp8"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid Background="Black">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <TextBlock Text="DYNAMIC XAML LOAD" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="25" Foreground="WhiteSmoke"></TextBlock>
        
        <Button Content="Button Test" FontSize="25" Grid.Row="1" Background="Azure" Name="Button1"></Button>

        <TextBlock Grid.Row="2" Text="UserControl1" VerticalAlignment="Center" HorizontalAlignment="Center" FontSize="25" Foreground="WhiteSmoke"></TextBlock>
            
    </Grid>
</UserControl>

x:Class="WpfApp8.UserControl1" 부분은 제거해 줘야 컴파일이 가능합니다.

cs파일이랑 떨어져 있어야 하며 cs파일은 제거합니다.

 

버튼을 하나 만들고 이름을 Button1으로 지정합니다.

 

3. 실행

UserControl1.xaml을 런타임중에 MainWindow에 붙인 모습

버튼을 클릭하면 연결한 클릭 이벤트에서 Added At Runtime을 확인 할 수 있습니다.

 

4. 소스파일

WpfApp8.zip
0.32MB

반응형

'C# > WPF' 카테고리의 다른 글

C# WPF 3D Button 꾸미기  (0) 2021.12.07
C# WPF Ripple Effect (원형으로 퍼져 나가는 효과)  (0) 2021.11.25