0
我正试图在XamarinForms PCL项目中创建一个通用的自定义控件,该控件相当于Windows 8/RT中的UserControl。XamarinForms TemplateBinding Equivalent
这是我到目前为止。
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这样:
首先,我在从内容查看继承控件创建的绑定属性
<Label Text="{TemplateBinding Title}" />
然而, TemplateBinding MarkupExtension不存在,所以我得到一个XamlParseException。
我已经可以想到一个解决方法,它使用x:Name =“MyLabel”命名标签,并使用newValue更改propertyChanged委托中的Text值,但有没有更好的方法来做到这一点?
我不需要这个控件的自定义渲染器,并且想尽可能在XAML中完成。提前致谢!
更新:皮特回答了它。只需使用{Binding}并正确设置BindingContext即可。
以下是我如何运作的。
var pageContent = new CustomControl();
pageContent.SetBinding (CustomControl.TitleProperty, new Binding(path: "Title"));
pageContent.BindingContext = new {Title = "This is the title that's databound!"};
看起来不像在BindableProperty的默认值工作,但..
感谢您的建议。我试过了,但没有奏效。我尝试了设置BindingContext,但它没有奏效。即使没有BindingContext,也应该显示“NO TITLE”,因为这是BindingProperty的默认值。 – dcdroid 2014-10-16 21:03:59
你有一个这样的小例子,你可以打包发送电子邮件,我会仔细看看?我的电子邮件在我的档案中。 – Pete 2014-10-16 21:07:47
在创建小示例应用程序中,事实证明你是对的。我需要做的就是正确设置BindingContext。更新了问题以反映这一点。谢谢! – dcdroid 2014-10-16 21:24:12