XAML 如何在Avalonia中从代码创建和显示Popup

yquaqz18  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(274)

从XAML我创建弹出窗口,但我需要从代码创建他。我的代码:

var popup = new Popup()
    {
        IsVisible = true,
        IsOpen = true,
        PlacementRect = new(50, 50, 100, 75),
        Child = new Border {
            BorderThickness = new(0.75),
            BorderBrush = Brushes.Black,
            Padding = new(6, 3),
            Child = new TextBlock
            {
                Background = Brushes.White,
                Text = textContent
            }
        }
    };
gopyfrb3

gopyfrb31#

1.创建自定义演示者

这个是我们数据的容器。

CustomPresenter.cs

using Avalonia;
using Avalonia.Controls.Primitives;

namespace AvaloniaPopup.Views
{
    public class CustomPresenter : PickerPresenterBase
    {
        public string Text
        {
            get => GetValue(TextProperty);
            set => SetValue(TextProperty, value);
        }

        public static readonly StyledProperty<string> TextProperty =
            AvaloniaProperty.Register<CustomPresenter, string>(nameof(Text));
    }
}

2.在宿主窗口中为我们的弹窗添加模板

MainWindow.axaml

<Window.Styles>
    <Style Selector="v|CustomPresenter">
        <Setter Property="Template">
        <ControlTemplate>
            <Border BorderThickness="0.75"
                    BorderBrush="Black"
                    Padding="6,3"
                    Background="White">
            <TextBlock Text="Hello World" />
            </Border>
        </ControlTemplate>
        </Setter>
    </Style>
</Window.Styles>

**重要提示:**不要忘记在窗口中声明命名空间

<Window ...
        xmlns:v="clr-namespace:AvaloniaPopup.Views;assembly=AvaloniaPopup">

3.将Popup和Presenter放入Window的AXAML代码中

MainWindow.axaml

<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<Button Content="Show Popup" Name="popupButton" Click="OnPopupButton_Click" />
<Popup Name="Popup"
    WindowManagerAddShadowHint="False"
    StaysOpen="False"
    PlacementMode="Bottom"
    PlacementTarget="{Binding ElementName=popupButton}">
<v:CustomPresenter />
</Popup>
</StackPanel>

4.创建代码隐藏Click方法打开Popup

MainWindow.axaml.cs

public partial class MainWindow : Window
{
    private Popup popup;

    public MainWindow()
    {
        InitializeComponent();
        popup = this.FindControl<Popup>("Popup");
    }

    private void OnPopupButton_Click(object sender, RoutedEventArgs e)
    {
        if (popup.IsOpen)
        {
            popup.IsOpen = false;
        }
        else
        {
            popup.IsOpen = true;
        }
    }
}

相关问题