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);
誰能幫助我與我的演示?
感謝您的回答,我會嘗試,TMR早晨。 – Gob00st
我在基類Control中找到BackgroundProperty,這就是爲什麼我沒有在Button屬性MSDN頁面中找到它:) – Gob00st