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