2012-11-25 157 views
5

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

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

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

回答

8

单向绑定

让我们假设你有静态属性NameCountry

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

现在想要绑定属性NameTextBlockTextProperty

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 */ 
      } 
     } 
    } 

,现在我们要这个属性Name结合TextBox,所以:

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(); 
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> 
相关问题