【问题标题】:How to bind a button's background color in c# code using setBinding function (instead in XAML code)如何使用 setBinding 函数在 c# 代码中绑定按钮的背景颜色(而不是在 XAML 代码中)
【发布时间】:2012-06-14 16:26:22
【问题描述】:

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

使用 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 的第一个参数是 依赖属性 但背景不是... 所以我在 Button 类中找不到合适的依赖属性 here.

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

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

  myText.SetBinding(TextBlock.TextProperty, myBinding);

谁能帮我做演示?

【问题讨论】:

    标签: c# xaml data-binding dependency-properties


    【解决方案1】:

    你有两个问题。

    1) BackgroundProperty 是一个静态字段,您可以访问该字段以进行绑定。

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

    将您的代码更改为:

    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;
            }
        }
    }
    

    【讨论】:

    • 我在基类 Control 中找到了 BackgroundProperty,这就是为什么我在 Button 属性 MSDN 页面中没有找到它的原因 :)
    猜你喜欢
    • 1970-01-01
    • 2010-12-30
    • 2011-03-07
    • 1970-01-01
    • 2012-03-22
    • 2011-09-28
    • 2019-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多