2014-10-16 48 views
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的默認值工作,但..

回答

1

我不知道如果這能幫助吧?

<Label Text="{Binding Title}"/> 

記得要設置BindingContext嗎?

+0

感謝您的建議。我試過了,但沒有奏效。我嘗試了設置BindingContext,但它沒有奏效。即使沒有BindingContext,也應該顯示「NO TITLE」,因爲這是BindingProperty的默認值。 – dcdroid 2014-10-16 21:03:59

+1

你有一個這樣的小例子,你可以打包發送電子郵件,我會仔細看看?我的電子郵件在我的檔案中。 – Pete 2014-10-16 21:07:47

+0

在創建小示例應用程序中,事實證明你是對的。我需要做的就是正確設置BindingContext。更新了問題以反映這一點。謝謝! – dcdroid 2014-10-16 21:24:12