2012-06-14 39 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

相關問題