I am basically doing a demo so don’t ask why.
It’s very easy to bind it using XAML:
c# code:
public class MyData
{
public static string _ColorName= "Red";
public string ColorName
{
get
{
_ColorName = "Red";
return _ColorName;
}
}
}
XAML code:
<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>
But I am trying to achieve the same binding use c# setBinding() function:
void createBinding()
{
MyData mydata = new MyData();
Binding binding = new Binding("Value");
binding.Source = mydata.ColorName;
this.button1.setBinding(Button.Background, binding);//PROBLEM HERE
}
The problem is in the last line as setBinding’s first parameter is a Dependency Property but Background is not… So I cannot find a suitable Dependency Property in Button class here.
this.button1.setBinding(Button.Background, binding);//PROBLEM HERE
But I can easily achieve similar thing for TextBlock as it has a Dependency Property
myText.SetBinding(TextBlock.TextProperty, myBinding);
Can anyone help me with my demo?
You have two problems.
1) The BackgroundProperty is a static field that you can access for the binding.
2) Additionally, when creating the binding object, the string you pass in is the name of the Property. The binding “source” is the class that contains this property. By using binding(“Value”) and passing it a string property, you were grabbing the value of the string. In this case, you need to grab the Color property (a Brush) of your MyData class.
Change your code to:
Add a Brush Property to your MyData Class: