【问题标题】:Static property Not Updating Data静态属性不更新数据
【发布时间】:2021-07-25 10:29:47
【问题描述】:
<Label x:Name="lbl" Text="{Binding Source={Static local:ViewModel.Texty}}"

这里是 ViewModel 类

public class DownloadDataPageViewModel : INotifyPropertyChanged
{
    public static event PropertyChangedEventHandler StaticPropertyChanged;

    private static void OnStaticPropertyChanged(string propertyName)
    {
        StaticPropertyChanged?.Invoke(null, 
            new PropertyChangedEventArgs(propertyName));
    }

    private static string _texty;

    public static string Texty
    {
        get => _texty;
       
        set
        {
            _texty = value;
            OnStaticPropertyChanged("Texty");
        }
    }
}

我面临的问题是它的标签显示“StaticCheckApp.ViewModel”而不是数据更改。

【问题讨论】:

  • INotifyPropertyChanged.PropertyChanged 事件未调用。
  • 这不是你应该使用的方式INotifyPropertyChanged。它旨在通知实例属性中的属性更改,而不是静态属性!另外Binding 关心PathBinding 内的属性更改通知。它的Source 将被计算一次,如果我没记错的话永远不会改变。
  • 我不确定如何实现这一点,我应该如何绑定到静态资源。我浏览了在线文档,我猜这是我能得到的最好的。
  • 这可能会有所帮助:another question
  • 您的 Texty 更新代码可能会有所帮助。

标签: c# xaml xamarin.forms


【解决方案1】:

要实现数据更改通知,您需要在 Xamarin.forms 中实现 INotifyPropertyChanged Interface

很遗憾,静态类无法实现接口,因此您的解决方案将无法正常工作。

通常,我创建类并实现 INotifyPropertyChanged 接口。

 public class DownloadDataPageViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    private string _texty;
    public string Texty
    {
        get => _texty;

        set
        {
            _texty = value;
            RaisePropertyChanged("Texty");
        }
    }
}

<ContentPage.Resources>
    <local:DownloadDataPageViewModel x:Key="model1" Texty="this is test" />

</ContentPage.Resources>
<ContentPage.Content>
    <StackLayout>
        <Label
            HorizontalOptions="CenterAndExpand"
            Text="{Binding Texty, Source={StaticResource model1}}"
            VerticalOptions="CenterAndExpand" />
    </StackLayout>
</ContentPage.Content>

如果你还想使用静态属性,可以看看:

Can't bind static property in XAML (Xamarin Forms)

【讨论】:

    猜你喜欢
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 2012-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多