【问题标题】:Button with glyp and label带有 glyp 和标签的按钮
【发布时间】:2020-12-02 15:11:27
【问题描述】:

我有一个带有 glyp 和标签(播放)的按钮。查看示例截图:

如果我点击按钮,操作系统会更改背景颜色并指示按下状态。此外,我将TapGestureRecognizer 添加到与按钮相同的事件的标签中。如果用户点击标签,则触发事件。到目前为止一切顺利。
问题是,如果我点击标签,如何绑定标签和按钮,以便按钮指示按下状态?

【问题讨论】:

  • 使用 ImageButton 绑定源图像并通过命令操作更改图像源。
  • 要更改按下状态,请尝试在每个平台上实现此功能。创建一个自定义 Button 并添加一个 bool 属性,例如 IsChecked。然后重写自定义渲染器类中的OnElementPropertyChanged,检测bool属性的值来改变按下状态。例如:protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); var customButton = Element as CustomButton; if (customButton.IsCheckeded) { Control.Pressed = true; } }
  • @y3z1 你能再解释一下吗。如果标签被按下,按钮必须处于按下状态。
  • 在自定义 Button 类中添加 IsChecked 属性,然后在自定义渲染器类中检测将 Control.Pressed 设置为 true 的值。public class CustomButton : Button { public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create(nameof(IsSelected), typeof(bool), typeof(CustomButton), null); public bool IsSelected { set => SetValue(IsSelectedProperty, value); get => (bool)GetValue(IsSelectedProperty); } }
  • 感谢您的帮助@y3z1。你为我指明了正确的方向!

标签: xaml xamarin xamarin.forms


【解决方案1】:

如何绑定标签和按钮,以便在点击标签时按钮指示按下状态

要更改按下状态,请尝试在每个平台上实现此功能。创建一个自定义按钮并添加一个 bool 属性,例如“IsChecked”。然后重写自定义渲染器类中的OnElementPropertyChanged,检测bool属性的值来改变按下状态。例如:

自定义控件类

public class CustomButton : Button 
{ 
    public static readonly BindableProperty IsSelectedProperty = BindableProperty.Create(nameof(IsSelected), typeof(bool), typeof(CustomButton), null); 
    public bool IsSelected 
    { 
        set => SetValue(IsSelectedProperty, value); 
        get => (bool)GetValue(IsSelectedProperty); 
    } 
}

自定义渲染器类

protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) 
{ 
    base.OnElementPropertyChanged(sender, e); 
    var customButton = Element as CustomButton; 
    if (customButton.IsCheckeded) 
    { 
        Control.Pressed = true; 
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-26
    • 2014-08-30
    • 2023-02-21
    • 2017-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多