gpt4 book ai didi

c# - WPF Popup 作为用 xaml 编写的单独控件

转载 作者:行者123 更新时间:2023-11-30 15:26:58 25 4
gpt4 key购买 nike

是否有机会创建一个 WPF Popup 作为单独的控件,使其不在窗口或用户控件内?

我有一个用 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();方法。

最佳答案

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

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

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

最简单的方法是

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

关于c# - WPF Popup 作为用 xaml 编写的单独控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28242963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com