[英]How to bind a button's background color in c# code using setBinding function (instead in XAML code)
I am basically doing a demo so don't ask why. 我基本上是在做一个演示,所以不要问为什么。
It's very easy to bind it using XAML: 使用XAML绑定它非常容易:
c# code: c#代码:
public class MyData
{
public static string _ColorName= "Red";
public string ColorName
{
get
{
_ColorName = "Red";
return _ColorName;
}
}
}
XAML code: 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>
But I am trying to achieve the same binding use c# setBinding() function: 但我试图实现相同的绑定使用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
}
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 . 问题出在最后一行,因为setBinding的第一个参数是依赖属性,但后台不是...... 所以我在 这里 找不到Button类中合适的依赖属性 。
this.button1.setBinding(Button.Background, binding);//PROBLEM HERE
But I can easily achieve similar thing for TextBlock as it has a Dependency Property 但我可以轻松地为TextBlock实现类似的东西,因为它具有依赖属性
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. 1)BackgroundProperty是一个静态字段,您可以访问绑定。
2) Additionally, when creating the binding object, the string you pass in is the name of the Property. 2)此外,在创建绑定对象时,传入的字符串是Property的名称。 The binding "source" is the class that contains this property.
绑定“source”是包含此属性的类。 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.
在这种情况下,您需要获取MyData类的Color属性(Brush)。
Change your code to: 将您的代码更改为:
MyData mydata = new MyData();
Binding binding = new Binding("Color");
binding.Source = mydata;
this.button1.SetBinding(Button.BackgroundProperty, binding);
Add a Brush Property to your MyData Class: 将一个Brush属性添加到MyData类:
public class MyData
{
public static Brush _Color = Brushes.Red;
public Brush Color
{
get
{
return _Color;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.