首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >XamarinForms TemplateBinding等价

XamarinForms TemplateBinding等价
EN

Stack Overflow用户
提问于 2014-10-16 20:25:00
回答 1查看 552关注 0票数 0

我试图在XamarinForms PCL项目中创建一个通用的自定义控件,该控件相当于Windows8/RT中的UserControl。

到目前为止我的情况是这样的。

首先,我在继承自ContentView的控件中创建了可绑定属性:

代码语言:javascript
复制
public static readonly BindableProperty TitleProperty =
        BindableProperty.Create<MyCustomControl, string> (
            p => p.Title, defaultValue: "NO TITLE", defaultBindingMode: BindingMode.TwoWay,
            validateValue: null,
            propertyChanged: (bindableObject, oldValue, newValue) =>
            {
                if (bindableObject != null)
                {

                }
                Logger.Instance.WriteLine ("TITLE PROPERTY CHANGED: OldValue = " + oldValue + " , NewValue = " + newValue);
            });

    public string Title { get { return (string)GetValue (TitleProperty); } set { SetValue (TitleProperty, value); } }

然后,我想在XAML中的标签中使用它:

代码语言:javascript
复制
<Label Text="{TemplateBinding Title}" />

但是,TemplateBinding MarkupExtension不存在,所以我得到了一个XamlParseException。

我已经想出了一个解决办法,就是用x:Name="MyLabel“命名标签,并用newValue更改propertyChanged委托中的文本值,但是有更好的方法吗?

对于此控件,我不需要自定义呈现器,如果可能的话,我希望使用XAML来完成所有操作。提前感谢!

更新:皮特回答了。只需使用{Binding }并正确设置BindingContext即可。

这是我如何让它起作用的。

代码语言:javascript
复制
            var pageContent = new CustomControl ();
        pageContent.SetBinding (CustomControl.TitleProperty, new Binding(path: "Title"));
        pageContent.BindingContext = new {Title = "This is the title that's databound!"};

不过,看起来BindableProperty中的默认值不起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-16 20:32:48

我不确定这是否有帮助?

代码语言:javascript
复制
<Label Text="{Binding Title}"/>

还记得设置BindingContext吗?

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26413271

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档