C# 将全局静态字符串绑定到 UWP Textblock

C# Binding global static string to UWP Textblock

各位。

有谁知道如何将全局静态字符串绑定到 UWP Textblock,并控制 propertychange 更新?

我尝试了很多东西,比如:

Text="{Binding Path={local:AppSettings.StorageFolder}, Mode=OneWay}"
Text="{x:Bind Path=(local:AppSettings.StorageFolder), RelativeSource={RelativeSource Self}, Mode=OneWay}"

并且 none 有效。总是会出现一些错误,例如: “不支持嵌套类型, 值不在预期范围内

我已经设法将它绑定到我 class 中的非静态值:

Text="{x:Bind viewModel.MyValue, Mode=OneWay}"

有什么解决办法吗?

谢谢。

您无法像在 WPF 中那样在 UWP 中简单地绑定到静态 属性。没有可用的 x:Static 标记扩展。

您有一些选择:

如果元素的 DataContext 是定义了静态 属性 的类型的实例,您可以像往常一样绑定到静态 属性:

<TextBlock Text="{Binding MyStaticProperty}" />

public sealed partial class BlankPage1 : Page
{
    public BlankPage1()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public static string MyStaticProperty { get { return "Static..."; } }
}

如果静态 属性 在另一个 class 中定义,您最好的选择是将静态 属性 包装在非静态中:

public sealed partial class BlankPage1 : Page
{
    public BlankPage1()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public static string MyWrapperProperty { get { return MyStaticClass.MyStaticProperty; } }
}

public static class MyStaticClass
{
    public static string MyStaticProperty { get { return "Static..."; } }
}

如果您想要 属性 更改通知,则绑定到静态 属性 根本没有意义,因为 [=33] 的 源对象 =] 必须实现 INotifyPropertyChanged 接口,以便您能够通过引发 PropertyChanged 事件动态刷新目标 属性。

您仍然可以将静态 属性 包装在实现 INotifyPropertyChanged 接口的视图模型的非静态之一中:

public class ViewModel : INotifyPropertyChanged
{
    public string MyNonStaticProperty
    {
        get { return MyStaticClass.MyStaticProperty; }
        set { MyStaticClass.MyStaticProperty = value; NotifyPropertyChanged(); }
    }

    //...
}

public static class MyStaticClass
{
    public static string MyStaticProperty { get; set; }
}

每当您想在视图中刷新目标 属性 时,您显然需要从视图模型 class 调用 NotifyPropertyChanged("MyNonStaticProperty")。

目前在 UWP 中,当使用 x:Bind 时,结束 属性(即在路径的末尾)必须是可变的/非静态的。但是,您可以在此之前引用静态属性,例如 x:Bind local:MyClass.Singleton.NonstaticProperty.

在x:Bind 属性 路径末尾使用函数也可以解决这种挑战。