2012-11-25 9 views
5

Jak programowo powiązać właściwości statyczne? Co mogę użyć w C#, abyJak programowo powiązać właściwości statyczne?

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

Aktualizacja: jest to możliwe do zrobienia OneWayToSource wiążąca? Rozumiem, że TwoWay nie jest możliwe, ponieważ nie ma żadnych zdarzeń aktualizacji na obiektach statycznych (przynajmniej w .NET 4). Nie mogę utworzyć instancji obiektu, ponieważ jest statyczny.

Odpowiedz

8

OneWay wiążące

Załóżmy, że masz klasę Country z własności statyczne Name.

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

a teraz chcesz właściwość wiązania do TextPropertyName z TextBlock.

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

Aktualizacja: TwoWay wiążące

Country klasy wygląda następująco:

public static class Country 
    { 
     private static string _name; 

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

A teraz chcemy wiążący tę właściwość Name do TextBox, więc:

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

Jeśli chcesz zaktualizować celu należy użyć BindingExpression i funkcji UpdateTarget:

Country.Name = "Poland"; 

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

Zawsze możesz napisać klasę non-static, aby zapewnić dostęp do jednego statycznego.

statyczne klasy: klasa

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

Non-static, aby zapewnić dostęp do właściwości statycznych.

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

wiązanie jest następnie prosta

<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> 
Powiązane problemy