【问题标题】:How can I bind a XAML element on a template with the C# back end instead of in the XAML?如何将模板上的 XAML 元素与 C# 后端而不是在 XAML 中绑定?
【发布时间】:2018-10-30 09:31:06
【问题描述】:

这是我现在拥有的:

我有这个针对问题进行了简化的模板:

<?xml version="1.0" encoding="UTF-8"?>
<Frame xmlns="http://xamarin.com/schemas/2014/forms" 
                      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
   xmlns:t="clr-namespace:Japanese.Templates" 
   xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
   x:Class="Japanese.Templates.RoundButtonText" x:Name="this">
   <Label Text="ABC"     
          TextColor="{Binding LabelTextColor, Source={x:Reference this}}"
   />
</Frame>

还有这个 C#

using Xamarin.Forms;

namespace Japanese.Templates
{
    public partial class RoundButtonText : BaseFrameButtonTemplate
    {
        public RoundButtonText()
        {
            InitializeComponent();
            // I would like to put the Label TextColor binding here instead of in the XAML
        }

    }
}

谁能帮助我,告诉我如何在 C# 后端添加标签 TextColor 的绑定,以便它以与当前编写时完全相同的方式更改:

 TextColor="{Binding LabelTextColor, Source={x:Reference this}}"

在 XAML 中?

【问题讨论】:

  • 您想从模板外部绑定颜色吗?
  • BaseFrameButtonTemplateControlTemplate 的子类吗?

标签: xamarin xamarin.forms


【解决方案1】:

从 XAML 中移除绑定并为 Label 控件提供一个 x:Name:

<?xml version="1.0" encoding="UTF-8"?>
<Frame xmlns="http://xamarin.com/schemas/2014/forms" 
       xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
       xmlns:t="clr-namespace:Japanese.Templates" 
       xmlns:local="clr-namespace:Japanese;assembly=Japanese" 
       x:Class="Japanese.Templates.RoundButtonText" x:Name="this">
    <Label x:Name="label" 
           Text="ABC" />
</Frame>

在后面的 C# 代码中设置绑定和要绑定的属性:

using Xamarin.Forms;

namespace Japanese.Templates
{
    public partial class RoundButtonText : BaseFrameButtonTemplate
    {
        Color _labelTextColor;
        public Color LabelTextColor {
            get {
                return _labelTextColor;
            } 
            set {
                if (_labelTextColor != value) {
                    _labelTextColor = value;
                    OnPropertyChanged("LabelTextColor");
                } 
            }
        }

        public RoundButtonText()
        {
            InitializeComponent();
            label.BindingContext = this;
            label.SetBinding(Label.TextColorProperty, "LabelTextColor");
        }
    }
}

现在,每当 LabelTextColor 属性值更改时,Label 的 TextColor 属性也应该更改,就像 XAML 绑定一样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    相关资源
    最近更新 更多