Hi, @fatih uyanık. Welcome to Microsoft Q&A.
Solution 1: Use a normal Class
instead of UserControl
with xaml
Create a normal Class
file and let it inherit UserControl.
public class MyUserControl:UserControl
{
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
Grid grid = new Grid();
ContentControl content = new ContentControl();
content.Name = "MyContentControl";
grid.Children.Add(content);
}
}
Use MyUserControl
in MainWindow.xaml.
<Grid>
<local: MyUserControl >
<StackPanel>
<TextBox x:Name="MyTextBox" Text="Hello" />
<Button x:Name="MyButton" Content="Click" />
</StackPanel>
</local: MyUserControl >
</Grid>
Solution 2: Use CustomControl
instead of UserControl
Create CustomControl
and let it inherit ContentControl.
public class MyCustomControl : ContentControl
{
static MyCustomControl()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl)));
}
}
Edit the corresponding Generic.xaml
file.
<Style TargetType="{x:Type local:MyCustomControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyCustomControl}">
<Grid>
<ContentControl Content="{TemplateBinding Content}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Use MyCustomControl
in MainWindow.xaml.
<Grid>
<local:MyCustomControl>
<StackPanel>
<TextBox x:Name="MyTextBox" Text="Hello" />
<Button x:Name="MyButton" Content="Click" />
</StackPanel>
</local:MyCustomControl>
</Grid>
For more detailed solutions, please refer to the document:Document Links
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.