【问题标题】:Xamarin.Forms - Possible to write custom renderer using original element name?Xamarin.Forms - 可以使用原始元素名称编写自定义渲染器吗?
【发布时间】:2017-07-28 13:42:03
【问题描述】:

在 Xamarin.Forms 中,通常我会使用“ButtonExt”之类的类名称为按钮编写自定义渲染器。是否可以使用元素的原始名称(我猜是覆盖)编写自定义渲染器,例如“Button”?

基本上,我希望能够为我的应用程序中的所有按钮添加水平填充,但不必将所有 Buttons 重命名为 ButtonExt(Xamarin.Forms 中的按钮没有 Padding 属性)。换句话说,我希望能够说 new Button { Padding = 20 } 而不必说 new ButtonExt { Padding = 20 }(项目是 C#,而不是 XAML)。

通常,在 iOS 项目中,我会:

[assembly: ExportRenderer(typeof(ButtonExt), typeof(ButtonExtRenderer))]
namespace StoreFulfillment.iOS
{
    public class ButtonExtRenderer : ButtonRenderer

在共享项目中,我有:

using MySharedProject;
using Xamarin.Forms;

namespace MySharedProject.Renderers
{
    public class ButtonExt : Button
    {
        ...

然后我会说new ButtonExt { Padding = 20 }。但是为了能写new Button { Padding = 20 },我不能写public class Button : Button……那我该怎么做呢?

【问题讨论】:

标签: xamarin xamarin.ios xamarin.forms custom-renderer


【解决方案1】:

当然!只需将其注册为普通的 Button 类型,并确保调用您覆盖的所有基本方法,以便原始工作也保留。

所以你注册渲染器的属性看起来像这样:

[assembly: ExportRenderer(typeof(Button), typeof(YourButtonRenderer))]

另外,请确保您确实需要自定义渲染器。如果您只想解决简单的样式问题,请查看 Xamarin.Forms styling possibilities,尤其是隐式样式。

【讨论】:

  • 感谢您的快速回复 - 将尝试。是的,我知道所有关于样式的知识,以及按钮如何 not 具有填充属性:)
  • 但是在 Xamarin 共享项目中,我将如何创建要添加自定义属性的类(即 Padding)?使用 ButtonExt,我将类声明为 public class ButtonExt : Button {... -- 我不能这样做 public class Button : Button...?
  • @jbyrd 您不能向已创建的类添加自定义属性,除非该类是 partial 类,而 Button 不是。因此,您可以选择,如您所说,创建扩展方法或创建 Attached Properties,这就是 Grid.Row 属性(这意味着 Button 类实际上没有 Button.Grid.Row 属性,但它可以仍然可以使用它)。我不认为我会使用附加属性来做你想做的事情,但它仍然是一个选项。
猜你喜欢
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 2014-08-29
  • 2016-05-31
  • 2014-08-10
  • 2018-01-21
  • 2016-07-10
  • 2017-01-07
相关资源
最近更新 更多