【问题标题】:Set Tag value in xaml在 xaml 中设置标记值
【发布时间】:2018-03-01 08:44:38
【问题描述】:

在 Xamarin 中,有没有办法在 xaml 文件中将标签设置为按钮?

我试过了,

<Button Text="OK"
 Tag="{Binding Email}"/>

但是在 xaml 中不支持 Tag 属性

xaml 中有什么属性支持设置标签值来查看

【问题讨论】:

  • 你想要一些按钮点击的价值,对吧?
  • 不,我想将值设置为标签,以便稍后我可以从类中检索

标签: xaml xamarin xamarin.forms


【解决方案1】:

您可以轻松创建自己的自定义Button 并添加标签BindableProperty

public class ButtonWithTag : Button
{
    public object Tag
    {
        get { return (object)GetValue(TagProperty); }
        set { SetValue(TagProperty, value); }
    }

    public static readonly BindableProperty TagProperty =
        BindableProperty.Create(nameof(Tag), typeof(object), typeof(ButtonWithTag), null);
}

你在 XAML 中这样使用它

xmlns:local="clr-namespace:YourProjectName"

    <local:ButtonWithTag 
        Text="Ok"
        Tag="{Binding Email}" />

【讨论】:

    【解决方案2】:

    您可以使用x:Name="MyButton",然后通过简单地使用MyButton.Text = "updated text" 来访问您的代码隐藏.cs 文件中的按钮。假设这就是你的意思。

    【讨论】:

    • 我不想设置我想设置标签的文本,它不应该显示在视图上。它应该存储在那个视图中,以便以后我可以检索相同的内容
    • 对,我只是用它作为例子。在那种情况下,我想你可以使用MyButton.Tag = ...
    • 标签属性在 xaml 中不支持。 xaml 中有什么属性可以设置标签
    • Xamarin Forms 没有用于视图的 Tag 属性。您可以创建自定义按钮渲染器,并添加您自己的 Tag 属性
    • 知道如何为标签属性进行自定义渲染
    【解决方案3】:

    我认为最好的解决方案是CommandParameter。您可以使用 CommandParameter 执行此操作。试试这个,

    .xaml

    <Button Text="OK"
            Command="{Binding TapCommand}"
            CommandParameter="EmailAddress"/>
    

    .cs

    ICommand tapCommand;
    
    public ICommand TapCommand {
        get { return tapCommand; }
    }
    
    public ConstructorName {
    tapCommand = new Command (OnTapped);
    }
    
    void OnTapped (object s)  {
        Debug.WriteLine ("parameter: " + s);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-27
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多