【问题标题】:Is there a way to activate a Button that exists within another class?有没有办法激活另一个类中存在的按钮?
【发布时间】:2023-01-04 23:24:59
【问题描述】:

我正在使用 C# 和 Xamarin。我有两个单独的班级。一个类本质上是用户界面,另一个类充当自定义构建的通用条目,供用户通过单击按钮输入数据和搜索结果。

主界面类:

Class MainPage
{
   public MainPage
   {
      Content = new StackLayout
      {
         Children =
         {
            new InputClass // This is my custom built user entry class
            {
            }.Invoke(ic => ic.Clicked += WhenButtonPressedMethod) // The problem is here, I can't figure out how to call the button within the input class to fire a clicked event.
         }
      }
   }
}

public async void WhenButtonPressedMethod (object sender, EventArgs e)
{
    // Supposed to do stuff when the button is pressed
}

输入类:

public class InputClass : Grid
{
   public delegate void OnClickedHandler(object sender, EventArgs e);
   public event OnClickHandler Clicked;

   public InputClass
   {
      Children.Add(
      new Button {}
      .Invoke(button => button.Clicked += Button_Clicked)
      )
   }

   private void Button_Clicked(object sender, EventArgs e)
   {
       Clicked?.Invoke(this, e);
   }
}

“InputClass”是一个网格,其中包含标题文本标签、条目和用户可以按下以提交和搜索数据的按钮。此类中的按钮是我试图实际访问以调用/引起单击事件的按钮,以便可以调用主 UI 类中的方法。但是,当我尝试在“InputClass”上调用单击事件时,我无法访问其中的按钮,我只能访问“InputClass”本身,它只是一个没有有用事件属性的网格。

任何解决方案或想法?


如果您遇到与此处提到的相同的问题,请遵循此页面上的代码并通读 cmet,它涵盖的内容足以将其拼凑在一起。

【问题讨论】:

  • InputClass 需要在按下消费者类可以订阅的按钮时引发自定义事件。消费者不需要知道 InputClass 内部的细节。
  • edit你的问题包括额外的细节或代码,不要把它塞进cmets
  • 是的,我已经尝试通过放置一个“Console.WriteLine("Button was clicked.")”进行调试,它确实可以到达并在 Button_Clicked 方法中打印出来。我还可以确认该事件为空。我放了一个 if 语句来检查 if(Clicked != null) 并且它是错误的。
  • @ToolmakerSteve 此外,永远不会调用 WhenButtonPressedMethod。这就是断开连接的地方。该事件始终为 null,并且由于 NullReferenceException 错误,当我不检查以确保它不为 null 时代码中断。
  • 我添加了一个答案,显示事件处理程序的“老派”分配。

标签: c# xamarin


【解决方案1】:

不知道为什么 fluent Invoke 不能正常工作。
以这种方式添加事件处理程序:

public MainPage
{
    var ic = new InputClass();
    ic.Clicked += WhenButtonPressedMethod;
    Content = new StackLayout
    {
        Children = { ic }
    }
}

public InputClass
{
    var button = new Button;
    button.Clicked += Button_Clicked;
    Children.Add(button);
}

【讨论】:

  • 我真的不好意思承认这一点......但问题完全在我这边。我将 .Clicked 事件附加到我的 MainPage 上错误的 InputClass 实例。因此,最终调用确实有效。我还假设您上面提供的方式也有效。我还没有实现它,但它看起来基本相同。无论如何,谢谢你的帮助。你和 Jason 仍然提供了足够的信息让我真正得到结果!
猜你喜欢
  • 2021-04-27
  • 2018-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多