gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:12:04 25 4
gpt4 key购买 nike

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

使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com