WPF user controls on multiple windows

B M-A 361 Reputation points
2022-08-25T18:47:39.347+00:00

Hello!
I have an WPF application with 5 windows and I want to put same user controls on all windows without copy and paste methods and style.
I saw that I can make a template and save it externally like in Xamarin, but what about the buttons methods?

Best regards,

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,669 questions
XAML
XAML
A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.
762 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 38,191 Reputation points Microsoft Vendor
    2022-08-26T06:39:13.507+00:00

    Hi,@B M-A . Could you describe more details about what about the buttons methods refers to? You could also see if the example below is what you want.

    1. Create a WPF User Control Library named WpfControlLibrary1.
      2.Then reference WpfControlLibrary1 in the project.
      UserControl1: <StackPanel Orientation="Horizontal">
      <Label x:Name="label" Content="Name" Width="100" Height="40"/>
      <TextBlock x:Name="tb" Width="100" Height="40" Text="Item1"/>
      <Button x:Name="btn" Content="Delete" Width="100" Height="40" Click="btn_Click"/>
      </StackPanel> public partial class UserControl1 : UserControl
      {
      public UserControl1()
      {
      InitializeComponent();
      }
      private void btn_Click(object sender, RoutedEventArgs e)
      {
      MessageBox.Show("Button Click");
      }
      }

    Project:

    <Window  
            xmlns:local="clr-namespace:UserControlInManyWindows"  
            xmlns:WpfControlLibrary1="clr-namespace:WpfControlLibrary1;assembly=WpfControlLibrary1" x:Class="UserControlInManyWindows.Window1"  
            mc:Ignorable="d"  
            Title="Window1" Height="450" Width="800">  
        <Grid>  
            <WpfControlLibrary1:UserControl1 HorizontalAlignment="Left" Margin="105,168,0,0" VerticalAlignment="Top"/>  
        </Grid>  
    </Window>  
    

    You could click UserControl to add it directly to multiple windows.
    235123-image.png


    If the response is helpful, please click "Accept Answer" and upvote it.
    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.


0 additional answers

Sort by: Most helpful