gpt4 book ai didi

c# - xamarin.forms 从 xaml 绑定(bind)到属性

转载 作者:可可西里 更新时间:2023-11-01 08:42:27 31 4
gpt4 key购买 nike

我是 xaml 绑定(bind)的新手,有时我真的不明白。

我的 xaml 中有这个:

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

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

我的 .cs 看起来像这样:

....
public bool IsLoading;

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

最佳答案

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

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

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

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

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 向下层叠可视化树,因此 ActivityIndi​​cator 控件将能够读取绑定(bind)中指定的属性。

编辑:Xamarin.Forms(和 Silverlight/WPF 等...抱歉,已经有一段时间了!)还提供了一个 SetBinding方法(请参阅数据绑定(bind)部分)。

关于c# - xamarin.forms 从 xaml 绑定(bind)到属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25912960/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com