在以下代码段中,我尝试将颜色(作为字符串)传递给控件并使用绑定将颜色分配给按钮的背景。但是,它被忽略了。知道出了什么问题吗?
这是 XAML:
<Window x:Class="SDKSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SDKSample"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<DockPanel.Resources>
<local:MyData x:Key="myDataSource" />
</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource myDataSource}" />
</DockPanel.DataContext>
<!--<Button Background="Red" Width="250" Height="25">RED</Button>-->
<Button Background="{Binding Source={StaticResource myDataSource}, Path=ColorName}" Width="150" Height="30">I'm bound to be red</Button>
</DockPanel>
</Window>
这是后面的代码:
namespace SDKSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
MyData md = new MyData("Red");
this.DataContext = md.ColorName;
}
}
public class MyData
{
private Color colorname;
public MyData()
{
}
public MyData(string value)
{
Color col = (Color)ColorConverter.ConvertFromString(value);
this.colorname = col;
}
public Color ColorName
{
get { return colorname; }
set
{
this.colorname = value;
}
}
}
}