2017-06-30 70 views
0

我想製作一個名爲switch label的自定義控件。我把標籤和開關放在堆棧佈局中。我的目的是做一個像SwitchCell的控制。背後Bindable屬性在StackLayout上不起作用

[XamlCompilation(XamlCompilationOptions.Compile)] 
public partial class SwitchLabel : StackLayout 
{ 
    public SwitchLabel() 
    { 
     BindingContext = this; 
     InitializeComponent(); 
    } 

    public static readonly BindableProperty TitleProperty = BindableProperty.Create(
     propertyName: nameof(Title), 
     returnType: typeof(string), 
     declaringType: typeof(SwitchLabel), 
     defaultValue: string.Empty, 
     defaultBindingMode: BindingMode.TwoWay); 

    public static readonly BindableProperty IsOnProperty = BindableProperty.Create(
     propertyName: nameof(IsOn), 
     returnType: typeof(bool), 
     declaringType: typeof(SwitchLabel), 
     defaultValue: false, 
     defaultBindingMode: BindingMode.TwoWay); 

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

    public bool IsOn 
    { 
     get 
     { 
      return (bool)GetValue(IsOnProperty); 
     } 
     set 
     { 
      SetValue(IsOnProperty, value); 
     } 
    } 
} 

<?xml version="1.0" encoding="UTF-8"?> 
<StackLayout xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      x:Class="MobileRKE.Controls.SwitchLabel" 
      Orientation="Horizontal"> 
    <Label x:Name="lbTitle" HorizontalOptions="FillAndExpand" Text="{Binding Title}" VerticalOptions="Center"/> 
    <Switch x:Name="swtValue" 
      IsToggled="{Binding IsOn}" 
      VerticalOptions="Start"/> 
</StackLayout> 

代碼做我把它寫在正確的方式? 我發現,當我綁定到它的模型綁定不會觸發

回答

0

我自己有困難的時間如何確切地可綁定屬性的工作。 但是,當我發生這種情況時,我將onPropertyChanged處理程序添加到BindableProperty.Create()作爲參數。並在視圖中反映控制權的變化。

無論如何,關於你的情況,我不認爲你需要添加可綁定的屬性,因爲IsToggled已經是一個可綁定的屬性。只需綁定到視圖模型中的布爾屬性,這應該工作。