【问题标题】:xamarin.forms binding from xaml to propertyxamarin.forms 从 xaml 绑定到属性
【发布时间】:2014-11-12 19:28:24
【问题描述】:

我是一个在 xaml 中使用绑定的新手,有时我真的不明白。

我的 xaml 中有这个:

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

绑定“IsLoading”。我在哪里声明/设置这个属性?!

我的 .cs 看起来像这样:

....
    public bool IsLoading;

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

【问题讨论】:

    标签: c# xaml xamarin.forms


    【解决方案1】:

    绑定通常从BindingContext 属性解析(在其他实现中,此属性称为DataContext)。默认情况下这是 null(至少在 XAML 的其他实现中),因此您的视图无法找到指定的属性。

    在您的情况下,您必须将BindingContext 属性设置为this

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

    但是,仅此还不够。您当前的解决方案没有实现任何属性更改通知视图的机制,因此您的视图必须实现INotifyPropertyChanged。相反,我建议你实现Model-View-ViewModel 模式,它不仅非常适合数据绑定,而且会产生更可维护和可测试的代码库:

    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(和 Silverlight/WPF 等...抱歉,已经有一段时间了!)还提供了一个 SetBinding 方法(请参阅数据绑定部分)。

    【讨论】:

    • Xamarin.Forms BindableObjects 没有DataContext 属性,而是BindingContext
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    相关资源
    最近更新 更多