inside
inside

Reputation: 3177

WPF Popup as a separate control written in xaml

Is there chance to create a WPF Popup as a separate control, so it is not inside a window or user control?

I have a popup written in XAML:

<Popup PopupAnimation="Fade" Name="MyPopup" MinWidth="200" MinHeight="100" Width="200" Height="100" Placement="Center" VerticalAlignment="Center" HorizontalAlignment="Center" IsEnabled="True" IsOpen="False">
        <Grid Width="Auto" Height="Auto" Background="Gray">
            <Grid.RowDefinitions>
                <RowDefinition Height="30"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
            <Border BorderThickness="2" CornerRadius="8" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.RowSpan="2">
                <Border.BorderBrush>
                    <SolidColorBrush Color="Gray"/>
                </Border.BorderBrush>
                <Border.Background>
                    <SolidColorBrush Color="White"/>
                </Border.Background>
            </Border>

            <StackPanel Grid.Row="0">
                <Label Foreground="Blue" Content="Popup_Title"/>
            </StackPanel>

            <GroupBox Grid.Row="1" Header="Popup example content">
                <StackPanel>

                </StackPanel>
            </GroupBox>
        </Grid>
    </Popup>

Now, on button click of my other control, I would like to do something like this:

private void Button_Click(object sender, RoutedEventArgs e)
    {
        PopupControl p = new PopupControl();
        p.IsOpen = true; 
    }

By looking at the example of UserControl or Window, I understand that I need to connect this popup with the actual c# class, something like:

public partial class PopupControl : Popup
{
    public PopupControl()
    {
        InitializeComponent();
    }
}

and then inside the Popup's XAML add class:

x:Class="WpfApplication1.PopupControl".

but two things:

1) There is no such a thing as x:Class for PopUp

2) Deriving from Popup won't have InitializeComponent(); method.

Upvotes: 3

Views: 3376

Answers (1)

Frank
Frank

Reputation: 4481

You almost got it right. While copy-pasting your Popup code in its own XAML file, you didn't add the necessary x namespace that contains the attached property x:Class:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

As soon as you add this to your root element (Popup), you can add x:Class="WpfApplication1.PopupControl". This will lead to the generation of a partial class in your obj folder that contains the InitializeComponent method that you were missing.

The easiest way to do that is by

  1. creating a new UserControl from the "Add Item" dialog.
  2. Then, rename the root element from UserControl to Popup.
  3. Finally, from the code behind class, just remove : UserControl.

Upvotes: 4

Related Questions