2012-11-25 10 views
5

Làm cách nào để liên kết với thuộc tính tĩnh theo lập trình? Tôi có thể sử dụng những gì trong C# để làmLàm cách nào để liên kết với thuộc tính tĩnh theo lập trình?

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

Cập nhật: là nó có thể làm OneWayToSource ràng buộc? Tôi hiểu rằng TwoWay là không thể vì không có sự kiện cập nhật trên các đối tượng tĩnh (ít nhất là trong .NET 4). Tôi không thể khởi tạo đối tượng vì nó là tĩnh.

Trả lời

8

OneWay ràng buộc

Giả sử rằng bạn có lớp Country với tài sản Name tĩnh.

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

Và bây giờ bạn muốn ràng buộc tài sản Name-TextProperty của TextBlock.

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

Cập nhật: TwoWay ràng buộc

Country lớp trông như thế này:

public static class Country 
    { 
     private static string _name; 

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

Và bây giờ chúng tôi muốn ràng buộc tài sản Name này để TextBox, vì vậy:

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

Nếu bạn muốn cập nhật mục tiêu mà bạn phải sử dụng BindingExpression và chức năng UpdateTarget:

Country.Name = "Poland"; 

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

Bạn luôn có thể viết một lớp không tĩnh để cung cấp truy cập vào một tĩnh.

lớp tĩnh: lớp

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

Non-tĩnh để cung cấp quyền truy cập vào các thuộc tính tĩnh.

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

Ràng buộc là sau đó đơn giản:

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