2012-11-25 5 views
5

Come eseguire il binding a proprietà statiche in modo programmatico? Cosa posso usare in C# per fareCome eseguire il bind alla proprietà statica a livello di codice?

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

Aggiornamento: è possibile fare OneWayToSource vincolante? Capisco che TwoWay non è possibile perché non ci sono eventi di aggiornamento su oggetti statici (almeno in .NET 4). Non riesco a creare un'istanza dell'oggetto perché è statico.

risposta

8

vincolante

OneWay Supponiamo di avere classe Country con proprietà statica Name.

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

e ora si vuole vincolante proprietà Name-TextProperty di TextBlock.

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

Aggiornamento: TwoWay vincolante

Country classe assomiglia a questo:

public static class Country 
    { 
     private static string _name; 

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

Ed ora vogliamo vincolante questa proprietà Name-TextBox, quindi:

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

Se si desidera aggiornare obiettivo è necessario utilizzare BindingExpression e la funzione UpdateTarget:

Country.Name = "Poland"; 

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

Si può sempre scrivere una classe non statica per fornire l'accesso a quella statica.

classe statica: classe

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

non statico per fornire l'accesso alle proprietà statiche.

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

legame è quindi semplice:

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