WPF绑定到现场 [英] WPF Binding to Field
问题描述
我已经试过几乎所有我在谷歌找到。但没有任何工程。
I have tried nearly everything I found on google. But nothing works.
我有此XAML:
<UserControl x:Class="Controller.General.Led"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Ellipse Name="ellipse" Fill="{Binding ElementName=Led, Path=backColor}" Stroke="Black" StrokeThickness="3">
</Ellipse>
</Grid>
这code:
public partial class Led : UserControl
{
public Brush backColor = Brushes.Red;
public Led()
{
InitializeComponent();
}
}
那么,为什么不工作的呢?
我也尝试了很多其他的解决方案,但没有什么工作。
So why doesn't this work? I also tried a lot of other solutions but nothing is working.
推荐答案
有两件事情错在这里,首先你不能只是设置的ElementName一类。一个快速简便的方法来解决这个问题只是设置了用户控制自己的数据上下文,因为它似乎这就是你要绑定停留的财产。另外,公共变量更改为属性(绑定否则不工作!)
A couple things wrong here, first you can't just set ElementName to a class. A quick easy way to fix this is just set the data context of your user control to itself, since it appears that's where the property you want to bind dwells. Also change the public variable to a PROPERTY (Binding does not work otherwise!)
public partial class Led : UserControl
{
public Brush backColor{get; set;}
public Led()
{
InitializeComponent();
this.DataContext = this;
backColor = Brushes.Red;
}
}
接下来只是改变你的XAML简单地读...
Next just alter your xaml to simply read...
<Ellipse
Name="ellipse"
Fill="{Binding backColor}"
Stroke="Black"
StrokeThickness="3"
/>
这篇关于WPF绑定到现场的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!