2012-06-14 41 views
3

我基本上在做一个演示,所以不要问为什么。如何使用setBinding函数(而不是XAML代码)在c#代码中绑定按钮的背景颜色

它非常容易使用XAML绑定它:

C#代码:

public class MyData 
    { 
     public static string _ColorName= "Red"; 

     public string ColorName 
     { 
      get 
      { 
       _ColorName = "Red"; 
       return _ColorName; 
      } 
     } 
    } 

XAML代码:

<Window x:Class="WpfApplication1.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:c="clr-namespace:WpfApplication1" 
     Title="MainWindow" Height="350" Width="525"> 
    <Window.Resources> 
     <c:MyData x:Key="myDataSource"/> 
    </Window.Resources> 

    <Window.DataContext> 
     <Binding Source="{StaticResource myDataSource}"/> 
    </Window.DataContext> 

    <Grid> 
     <Button Background="{Binding Path=ColorName}" 
      Width="250" Height="30">I am bound to be RED!</Button> 
    </Grid> 
</Window> 

但我想达到同样的结合使用C#setBinding( )功能:

 void createBinding() 
     { 
      MyData mydata = new MyData(); 
      Binding binding = new Binding("Value"); 
      binding.Source = mydata.ColorName; 
      this.button1.setBinding(Button.Background, binding);//PROBLEM HERE    
     } 

问题是在最后一行setBinding的第一个参数是依赖属性但背景不是... 所以我无法在按钮类here找到合适的依赖属性。

 this.button1.setBinding(Button.Background, binding);//PROBLEM HERE    

但我可以很容易地实现类似的事情TextBlock的,因为它有一个依赖属性

myText.SetBinding(TextBlock.TextProperty, myBinding); 

谁能帮助我与我的演示?

回答

2

你有两个问题。

1)BackgroundProperty是一个静态字段,您可以访问该绑定。

2)另外,在创建绑定对象时,您传递的字符串是该属性的名称。绑定“源”是包含此属性的类。通过使用绑定(“Value”)并传递一个字符串属性,您可以获取字符串的值。在这种情况下,您需要获取MyData类的Color属性(画笔)。

你的代码更改为:

MyData mydata = new MyData(); 
Binding binding = new Binding("Color"); 
binding.Source = mydata; 
this.button1.SetBinding(Button.BackgroundProperty, binding); 

添加刷属性您MyData的类:

public class MyData 
{ 
    public static Brush _Color = Brushes.Red; 
    public Brush Color 
    { 
     get 
     { 
      return _Color; 
     } 
    } 
} 
+0

感谢您的回答,我会尝试,TMR早晨。 – Gob00st

+0

我在基类Control中找到BackgroundProperty,这就是为什么我没有在Button属性MSDN页面中找到它:) – Gob00st

相关问题