我试图在XamarinForms PCL项目中创建一个通用的自定义控件,该控件相当于Windows8/RT中的UserControl。
到目前为止我的情况是这样的。
首先,我在继承自ContentView的控件中创建了可绑定属性:
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委托中的文本值,但是有更好的方法吗?
对于此控件,我不需要自定义呈现器,如果可能的话,我希望使用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中的默认值不起作用。
发布于 2014-10-16 20:32:48
我不确定这是否有帮助?
<Label Text="{Binding Title}"/>还记得设置BindingContext吗?
https://stackoverflow.com/questions/26413271
复制相似问题