【问题标题】:Xamarin Custom Renderer for Button (iOS)用于按钮 (iOS) 的 Xamarin 自定义渲染器
【发布时间】:2018-03-15 06:28:21
【问题描述】:

我已经为 iOS(和 Android - 工作正常)声明了一个自定义渲染器。

自定义渲染器主要是设置背景颜色和文字颜色。

设置文本颜色适用于启用和禁用状态,但我在为不同状态下的按钮设置背景颜色时遇到问题。

我无法找到涵盖此内容的 Xamarin 自定义渲染器的任何文档,这是 Xamarin 的一个已知错误,我无法在 Visual Studio 中获得任何适用于 iOS 类的智能感知,到目前为止,我使用了哪些资源我可以找到该主题。

    public class MyButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            if (Control != null)
            {
                Control.BackgroundColor= UIColor.FromRGB(235, 115, 17);

                Control.SetTitleColor(UIColor.FromRGB(255, 255, 255),UIControlState.Normal);
                Control.SetTitleColor(UIColor.FromRGB(0, 0, 0),UIControlState.Disabled);
            }
        }
    } 

如果按钮 UIControlStateDisabled,我希望能够将背景颜色更改为我设置的其他颜色。

在此图像中,按钮使用自定义渲染器。顶部按钮被禁用,底部按钮被启用。正如您可能猜到的,我想让禁用的按钮变为灰色。

我相信这一定很简单,但缺乏文档和没有智能的问题阻碍了我的努力。

【问题讨论】:

    标签: c# button xamarin.ios xamarin.forms custom-renderer


    【解决方案1】:

    您可以覆盖OnElementPropertyChanged 以跟踪属性更改。

    protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
    {
        base.OnElementChanged(e);
    
        ....
    
        UpdateBackground();
    }
    
    protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        base.OnElementPropertyChanged(sender, e);
    
        if (e.PropertyName == VisualElement.IsEnabledProperty.PropertyName)
            UpdateBackground();
    }
    
    void UpdateBackground()
    {
        if (Control == null || Element == null)
            return;
    
        if (Element.IsEnabled)
            Control.BackgroundColor = ..;
        else
            Control.BackgroundColor = ..;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-07-23
      • 1970-01-01
      • 2017-06-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-16
      • 1970-01-01
      • 2021-04-04
      相关资源
      最近更新 更多