2012-11-25 2 views
5

Wie programmgesteuert an statische Eigenschaft binden? Was kann ich in C# verwendenWie programmgesteuert an statische Eigenschaft binden?

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

-Update zu machen: ist es möglich, OneWayToSource Bindung zu tun? Ich verstehe, dass TwoWay nicht möglich ist, da es keine Update-Ereignisse für statische Objekte gibt (zumindest in .NET 4). Ich kann kein Objekt instantiieren, weil es statisch ist.

Antwort

8

OneWay Bindung

Nehmen wir an, dass Sie Klasse haben Country mit statische Eigenschaft Name.

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

Und jetzt Sie wollen Bindungseigenschaft Name-TextProperty von TextBlock.

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

Update: TwoWay Bindung

Country Klasse sieht wie folgt aus:

public static class Country 
    { 
     private static string _name; 

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

Und jetzt wollen Bindung wir diese Eigenschaft Name-TextBox, so:

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); 

Wenn Sie Ziel aktualisieren möchten, müssen Sie BindingExpression und Funktion UpdateTarget:

Country.Name = "Poland"; 

BindingExpression be = BindingOperations.GetBindingExpression(this.tbCountry, TextBox.TextProperty); 
be.UpdateTarget(); 
0

Sie immer eine nicht-statische Klasse schreiben könnte Zugriff auf die statische bereitzustellen.

Statische Klasse:

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

Nicht statische Klasse Zugriff auf statische Eigenschaften bereitzustellen.

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

Bindung ist dann einfach:

<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>