5

如何以编程方式绑定到静态属性?我可以在 C# 中使用什么来制作

{Binding Source={x:Static local:MyClass.StaticProperty}}

更新:是否可以进行 OneWayToSource 绑定?我知道 TwoWay 是不可能的,因为静态对象上没有更新事件(至少在 .NET 4 中)。我无法实例化对象,因为它是静态的。

4

2 回答 2

8

单向绑定

让我们假设您有Country具有静态属性的类Name

public class Country
{
  public static string Name { get; set; }
}

现在您希望将属性绑定NameTextPropertyof TextBlock

Binding binding = new Binding();
binding.Source = Country.Name;
this.tbCountry.SetBinding(TextBlock.TextProperty, binding);

更新:双向绑定

Country类看起来像这样:

public static class Country
    {
        private static string _name;

        public static string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                Console.WriteLine(value); /* test */
            }
        }
    }

现在我们想将此属性绑定NameTextBox,所以:

Binding binding = new Binding();
binding.Source = typeof(Country);
binding.Path = new PropertyPath(typeof(Country).GetProperty("Name"));
binding.Mode = BindingMode.TwoWay;
binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
this.tbCountry.SetBinding(TextBox.TextProperty, binding);

如果要更新目标,则必须使用BindingExpression和功能UpdateTarget

Country.Name = "Poland";

BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty);
be.UpdateTarget();
于 2012-11-25T09:47:26.477 回答
0

您总是可以编写一个非静态类来提供对静态类的访问。

静态类:

namespace SO.Weston.WpfStaticPropertyBinding
{
    public static class TheStaticClass
    {
        public static string TheStaticProperty { get; set; }
    }
}

提供对静态属性的访问的非静态类。

namespace SO.Weston.WpfStaticPropertyBinding
{
    public sealed class StaticAccessClass
    {
        public string TheStaticProperty
        {
            get { return TheStaticClass.TheStaticProperty; }
        }
    }
}

绑定很简单:

<Window x:Class="SO.Weston.WpfStaticPropertyBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SO.Weston.WpfStaticPropertyBinding"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <local:StaticAccessClass x:Key="StaticAccessClassRes"/>
    </Window.Resources>
    <Grid>
        <TextBlock Text="{Binding Path=TheStaticProperty, Source={StaticResource ResourceKey=StaticAccessClassRes}}" />
    </Grid>
</Window>
于 2012-11-25T10:59:40.937 回答