Skip to main content
 首页 » 编程设计

c#之按钮的 Xamarin 自定义渲染器 (iOS)

2024年02月27日75cloudgamer

我已经为 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); 
            } 
        } 
    }  

如果按钮 UIControlState 为 Disabled,我希望能够将背景颜色更改为我设置的颜色以外的颜色。

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

我相信这一定非常简单,但缺乏文档和无智能感知问题阻碍了我的努力。

请您参考如下方法:

您可以覆盖 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 = ..; 
}