【问题标题】:WPF Popup as a separate control written in xamlWPF Popup 作为用 xaml 编写的单独控件
【发布时间】:2015-01-30 19:07:35
【问题描述】:

是否有机会将 WPF 弹出窗口创建为单独的控件,因此它不在窗口或用户控件内?

我有一个用 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>

现在,在我的另一个控件的按钮单击时,我想做这样的事情:

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

通过查看 UserControl 或 Window 的示例,我了解到我需要将此弹出窗口与实际的 c# 类连接起来,例如:

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

然后在 Popup 的 XAML 中添加类:

x:Class="WpfApplication1.PopupControl"。

但有两件事:

1) 没有 x:Class for PopUp 这样的东西

2) 从 Popup 派生不会有 InitializeComponent();方法。

【问题讨论】:

    标签: c# .net wpf xaml popup


    【解决方案1】:

    你几乎猜对了。在将 Popup 代码复制粘贴到其自己的 XAML 文件中时,您没有添加包含附加属性 x:Class 的必要 x 命名空间:

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

    将其添加到根元素(弹出窗口)后,您就可以添加x:Class="WpfApplication1.PopupControl"。这将导致在您的 obj 文件夹中生成一个部分类,其中包含您缺少的 InitializeComponent 方法。

    最简单的方法是通过

    1. 从“添加项目”对话框创建一个新的UserControl
    2. 然后,将根元素从 UserControl 重命名为 Popup
    3. 最后,从类后面的代码中删除: UserControl

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-18
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      • 2020-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多