繁体   English   中英

如何在具有C#后端而不是XAML的模板上绑定XAML元素?

[英]How can I bind a XAML element on a template with the C# back end instead of in the XAML?

这是我现在所拥有的:

我有一个简化了此问题的模板:

<?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中?

从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绑定一样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM