2014-09-18 11 views
11

मैं xaml में बाइंडिंग के साथ कुल नौसिखिया हूं और मुझे कभी-कभी इसे कभी नहीं मिलता है।xamarin.forms xaml से संपत्ति के लिए बाध्यकारी

मैं अपने XAML में यह है:

<ActivityIndicator IsRunning="{Binding IsLoading}" IsVisible="{Binding IsLoading}" /> 

बाइंडिंग "IsLoading"। मैं इस संपत्ति को कहां घोषित/सेट करूं ?!

मेरे .cs इस तरह दिखता है:

.... 
    public bool IsLoading; 

    public CardsListXaml() 
    { 
     InitializeComponent(); 
     IsLoading = true; 
.... 

उत्तर

12

बाइंडिंग आम तौर पर BindingContext संपत्ति से हल कर रहे हैं (अन्य कार्यान्वयन में, इस संपत्ति DataContext कहा जाता है)। डिफ़ॉल्ट रूप से यह null है (कम से कम XAML के अन्य कार्यान्वयन में), इस प्रकार आपका दृश्य निर्दिष्ट गुणों को ढूँढने में असमर्थ है।

आपके मामले में, आप this को BindingContext गुण सेट करना होगा:

public CardsListXaml() 
{ 
    InitializeComponent(); 
    BindingContext = this; 
    IsLoading = true; 
} 

बहरहाल, यह अकेले पर्याप्त नहीं होगा। आपका वर्तमान समाधान किसी भी संपत्ति परिवर्तन के दृश्य को सूचित करने के लिए एक तंत्र को लागू नहीं करता है, इसलिए आपके विचार को INotifyPropertyChanged लागू करना होगा। इसके बजाय, मैं सुझाव है कि आप Model-View-ViewModel पैटर्न, जो न केवल डेटा बाइंडिंग के साथ खूबसूरती से फिट बैठता है को लागू है, लेकिन एक और अधिक maintainable और परीक्षण योग्य कोड बेस में परिणाम होगा:

public class CardsListViewModel : INotifyPropertyChanged 
{ 
    private bool isLoading; 
    public bool IsLoading 
    { 
     get 
     { 
      return this.isLoading; 
     } 

     set 
     { 
      this.isLoading = value; 
      RaisePropertyChanged("IsLoading"); 
     } 
    } 

    public CardsListViewModel() 
    { 
     IsLoading = true; 
    } 

    //the view will register to this event when the DataContext is set 
    public event PropertyChangedEventHandler PropertyChanged; 

    public void RaisePropertyChanged(string propName) 
    { 
     if (PropertyChanged != null) 
     { 
      PropertyChanged(this, new PropertyChangedEventArgs(propName)); 
     } 
    } 
} 

और फिर अपने कोड-पीछे के निर्माता में:

public CardsListView() 
{ 
    InitializeComponent(); 
    BindingContext = new CardsListViewModel(); 
} 

बस स्पष्ट करने के लिए, DataContext दृश्य पेड़ को कैस्केड करता है, इस प्रकार ActivityIndicator नियंत्रण बाइंडिंग में निर्दिष्ट गुणों को पढ़ने में सक्षम होगा।

संपादित करें: Xamarin.Forms (और सिल्वरलाइट/WPF आदि ... खेद है, यह एक समय हो गया है!) भी एक SetBinding विधि (देखें डाटा अनुभाग बाइंडिंग) प्रदान करता है।

+1

'Xamarin.Forms' 'BindableObject के पास 'DataContext' गुण नहीं हैं, लेकिन' BindingContext' –

+0

जानकारी के लिए धन्यवाद! –

संबंधित मुद्दे