问题
I have tried nearly everything I found on google. But nothing works.
I have this 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>
And this 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.
回答1:
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;
}
}
Next just alter your xaml to simply read...
<Ellipse
Name="ellipse"
Fill="{Binding backColor}"
Stroke="Black"
StrokeThickness="3"
/>
回答2:
When you use ElementName=Led
, you're telling WPF to look for an element named Led
, however you haven't declared an element with that name.
KDiTraglia's answer is the correct way to go, but setting a name for your user control would also work:
<UserControl x:Name="Led" ...>
....
</UserControl>
来源:https://stackoverflow.com/questions/10523915/wpf-binding-to-field