c# - 如何使用 setBinding 函数(而不是 XAML 代码)在 C# 代码中绑定(bind)按钮的背景颜色

标签 c# xaml data-binding dependency-properties

我基本上是在做演示所以不要问为什么。

使用 XAML 绑定(bind)它非常容易:

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() 函数实现相同的绑定(bind):

        void createBinding()
        {
            MyData mydata = new MyData();
            Binding binding = new Binding("Value");
            binding.Source = mydata.ColorName;
            this.button1.setBinding(Button.Background, binding);//PROBLEM HERE             
        }

问题出在最后一行,因为 setBinding 的第一个参数是一个Dependency Property 但 Background 不是... 所以我在 Button 类中找不到合适的 Dependency Property here .

        this.button1.setBinding(Button.Background, binding);//PROBLEM HERE             

但是我可以很容易地为 TextBlock 实现类似的事情,因为它有一个依赖属性

  myText.SetBinding(TextBlock.TextProperty, myBinding);

谁能帮我演示一下?

最佳答案

你有两个问题。

1) BackgroundProperty 是一个静态字段,您可以为绑定(bind)访问它。

2)另外,在创建绑定(bind)对象时,你传入的字符串就是Property的名称。绑定(bind)“源”是包含此属性的类。通过使用 binding("Value") 并向其传递一个字符串属性,您可以获取字符串的值。在这种情况下,您需要获取 MyData 类的 Color 属性(画笔)。

将您的代码更改为:

MyData mydata = new MyData();
Binding binding = new Binding("Color");
binding.Source = mydata;
this.button1.SetBinding(Button.BackgroundProperty, binding);

将 Brush 属性添加到您的 MyData 类:

public class MyData
{
    public static Brush _Color = Brushes.Red;
    public Brush Color
    {
        get
        {
            return _Color;
        }
    }
}

关于c# - 如何使用 setBinding 函数(而不是 XAML 代码)在 C# 代码中绑定(bind)按钮的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11037366/

相关文章:

c# - 如何在 IActionFilter Asp.net core 中读取 OnActionExecuting(ActionExecutingContext context) 中的请求体

c# - 以编程方式将工具提示放在 ListBox 类上

c# - 从位图设置图像

c# - 带有自定义刻度的 slider (标签和速度)

wpf - 在 Silverlight/WPF 按钮上设置 MouseOver 的样式

java - android 数据绑定(bind) - 找不到类 android.view.data

c# - Sharepoint + Javascript,将列表项移动/复制到另一个文件夹

xaml - wpf 中的超链接

c# - 如何在 VS WPF 设计面板中显示集合数据?

c# - 绑定(bind)不响应 PropertyChanged