WPF Binding to Field

我的未来我决定 提交于 2019-12-30 14:16:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!