2012-11-25 16 views
5

प्रोग्रामिक रूप से स्थैतिक संपत्ति से कैसे जुड़ें? मैं सी # में क्या उपयोग कर सकते हैं बनाने के लिएप्रोग्रामिक रूप से स्थैतिक संपत्ति से कैसे जुड़ें?

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

अद्यतन: यह संभव है बाध्यकारी OneWayToSource करना है? मैं समझता हूं कि दोवे संभव नहीं है क्योंकि स्थिर वस्तुओं पर कम से कम कोई अपडेट नहीं है (कम से कम .NET 4 में)। मैं ऑब्जेक्ट को तुरंत चालू नहीं कर सकता क्योंकि यह स्थैतिक है।

उत्तर

8

Oneway बाध्यकारी

मान लें कि आप स्थिर संपत्ति Name साथ वर्ग Country करते हैं।

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

और अब आप TextBlock की TextProperty को संपत्ति Name बाध्यकारी चाहते हैं।

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

अद्यतन: TwoWay बाध्यकारी

Country वर्ग इस तरह दिखता है:

public static class Country 
    { 
     private static string _name; 

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

और अब हम TextBox को यह संपत्ति Name बाध्यकारी चाहते हैं, इसलिए:

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> 
संबंधित मुद्दे