【问题标题】:Adding tap behavior to Xamarin label将点击行为添加到 Xamarin 标签
【发布时间】:2020-10-17 13:07:21
【问题描述】:

我在一个页面上有几个带有文本的标签。当我点击一个标签时,我会显示一个带有特定标题的单独页面,以编辑点击的标签内容。

我使用了Label.GestureRecognizers 并调用了与每个标签相关联的不同命令。

我想统一这个方法,去掉所有这些特定的命令,并有一个通用的行为,附加到一个标签上,页面标题将作为参数传递给这个行为。

当我点击/点击这个标签时,这个行为应该做我想做的事情。

我的行为类是这样的:

public class EditTextBehavior : Behavior<Label>
{
    public string PageTitle { get; set; }
    
    protected override void OnAttachedTo(Label bindable)
    {
        base.OnAttachedTo(bindable);

        // I would like to bind tap/click event to label here ('bindable' method parameter)
        // but label does not have onClick or onTap events 
        // Focused event do not work as expected.

    }

    protected override void OnDetachingFrom(Label bindable)
    {
        base.OnDetachingFrom(bindable);
        // Performing cleanup here
    }
}

我在 xaml-page 中使用它,放入标签元素中,如下所示:

  <Label.Behaviors>
      <behaviors:EditTextBehavior PageTitle="Some title"/>
  </Label.Behaviors>

我的问题:进入OnAttachedTo()行为类的方法我想给标签点击/点击事件附加一个处理程序,来处理这个点击/点击事件并做一些事情。

我该怎么做?

用命令代替行为并不方便,因为每个标签都有很多参数。

【问题讨论】:

  • 如何创建一个继承标签的自定义控件。然后将 Bindeable 属性添加到该控件。也许一个参数 = 一个 Bindeable 属性。
  • 使用此c-sharpcorner.com/article/… 并将您的点击连同所有参数重定向到您的视图模型
  • @ShubhamTyagi 谢谢。我的代码中有event-to- command behavior,在这种情况下,xaml 代码看起来就像我使用带有命令的Label.GestureRecognizers。它没有帮助,因为 Command 只允许一个参数,并且这个参数应该是一个字符串。否则,如果此参数不是字符串,并且引用视图模型中的对象,则该命令不会执行。

标签: c# xaml xamarin.forms


【解决方案1】:

你说的很多参数是什么意思。就像你提到的页面标题一样,你能举出更多例子吗? 这是你想要的吗 具有可绑定属性的自定义标签。

<MyCustomLabel x:Name="myLabel1" PageTitle="My Title" Param2="second Param" Param3="3" ...>
   <MyCustomLabel.GestureRecognizer>
     <TapGestureRecognizer Command={Binding TapCommand} CommandParameter={x:Reference myLabel1}/>
   </MyCustomLabel.GestureRecognizer>
</MyCustomLabel>

视图模型

public ICommand TapCommand{get;set;}
...
TapCommand = new Command<object>(OnLabelTapped)
...
private void OnLabelTapped(object obj)
{
  if(obj is MyCustomLabel myLabel)
  {
     string title = mylabel.PageTitle;
     int value = myLabel.Param3;
     ...
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多