You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中访问泛型基类类型参数的属性?

解决方案:访问泛型参数类的属性

你的核心问题是:派生类ForgotPasswordDialog继承自Popup<PopupDialog>,需要访问泛型参数PopupDialog中的IsBackDismissEnabled属性。由于IsBackDismissEnabled属于泛型参数的类型,而非Popup<T>基类本身,不能直接通过base访问,可通过以下方式实现:

方法1:通过Result属性访问

Xamarin.CommunityToolkit的Popup<T>类中,Result属性用于存储弹窗的返回数据,其类型就是你指定的泛型参数PopupDialog。你可以先实例化PopupDialog并赋值给Result,再访问它的属性:

using Xamarin.CommunityToolkit.UI.Views;

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ForgotPasswordDialog : Popup<PopupDialog>
{
    public ForgotPasswordDialog()
    {
        InitializeComponent();

        // 实例化PopupDialog并赋值给Result
        this.Result = new PopupDialog();
        // 访问并设置IsBackDismissEnabled属性
        this.Result.IsBackDismissEnabled = true;
    }
}

方法2:结合弹窗返回按钮事件使用

如果你的IsBackDismissEnabled是用来控制返回按钮是否关闭弹窗的,还可以配合Popup的BackButtonPressed事件实现逻辑:

using Xamarin.CommunityToolkit.UI.Views;

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ForgotPasswordDialog : Popup<PopupDialog>
{
    public ForgotPasswordDialog()
    {
        InitializeComponent();

        this.Result = new PopupDialog { IsBackDismissEnabled = true };
        this.BackButtonPressed += ForgotPasswordDialog_BackButtonPressed;
    }

    private void ForgotPasswordDialog_BackButtonPressed(object sender, BackButtonPressedEventArgs e)
    {
        // 根据自定义属性判断是否阻止默认关闭行为
        if (this.Result != null && !this.Result.IsBackDismissEnabled)
        {
            e.Handled = true; // 阻止弹窗关闭
        }
    }
}

方法3:作为绑定上下文使用

如果需要在XAML中也绑定这个属性,可以将PopupDialog实例设置为弹窗的BindingContext:

using Xamarin.CommunityToolkit.UI.Views;

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ForgotPasswordDialog : Popup<PopupDialog>
{
    public ForgotPasswordDialog()
    {
        InitializeComponent();

        var dialogModel = new PopupDialog { IsBackDismissEnabled = true };
        this.BindingContext = dialogModel;
        this.Result = dialogModel;
    }
}

关键说明

base关键字指向的是Popup<PopupDialog>基类,而IsBackDismissEnabled是你自定义的PopupDialog类的属性,不属于Popup<T>基类,因此不能用base.IsBackDismissEnabled的方式访问。必须通过泛型Popup<T>提供的Result属性(或自行创建的PopupDialog实例)来访问该属性。

内容的提问来源于stack exchange,提问作者Junaid Pathan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 06:15:39