WPF绑定到普通属性 - 不工作

问题描述:

我有一个控制位置,我想将颜色绑定到它自己的类中的普通属性。WPF绑定到普通属性 - 不工作

但它无法工作?任何线索?

我有这个

public Brush SeperatorColour 
    { 
     get { return (Brush)GetValue(SeperatorColourProperty); } 
     set { SetValue(SeperatorColourProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for SeperatorColour. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty SeperatorColourProperty = 
     DependencyProperty.Register("SeperatorColour", typeof(Brush), typeof(TycoMessageBarMessage), new UIPropertyMetadata(Brushes.Crimson)); 

<StackPanel Orientation="Horizontal" Background="Black" > 
    <Rectangle Name="MessageSeperator" Height="auto" Width="10" Fill="{Binding Path=SeperatorColour, ElementName=container, Mode=OneTime}" /> 
    <TextBlock Name="MessageText" Text="Hello" Foreground="White" Margin="5,0" /> 
</StackPanel> 
+0

希望你设置下调试DataContext的 – 2011-04-06 15:15:39

+3

照照输出窗口在Visual Studio中。应该有绑定错误。 – 2011-04-06 15:18:44

+0

其中一个可以通过先了解基础知识轻松解决的问题之一:http://msdn.microsoft.com/en-us/library/ms752347.aspx – 2011-04-06 15:48:04

的ElementName =容器

意味着你要绑定到名为 '容器' 另一XAML元素,你会可能想用'SeperatorColour'属性绑定到对象的某个实例。

如果您不绑定到另一个XAML元素,请不要将“ElementName”添加到绑定表达式中。

+0

我已经删除了“ElementName” - 仍然没有喜悦 – Kaya 2011-04-06 15:36:55

+0

需要以某种方式将数据绑定到“this”? – Kaya 2011-04-06 15:37:20

+0

数据上下文在这里很重要。 – 2011-04-06 23:09:02

您可能需要您的控件的名称设置为container

<UserControl xmlns="..." 
      x:Name="container"> 

或相对使用绑定:

Fill="{Binding Path=SeperatorColour, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyControl}}, Mode=OneTime}" 

在这里,而不是MyControl你需要指定你的控制类型。

在情况下,如果它是一个自定义的控制,你已经证明位于该控制的控制模板中的XAML,那么你可以使用TemplateBinding

Fill="{TemplateBinding SeperatorColour}" 

这应该很好地工作,如果你有正确设置您的用户控件的DataContext -

<Rectangle Name="MessageSeperator" Height="auto" Width="10" Fill="{Binding Path=SeperatorColour, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" /> 

你在运行你的应用程序的输出窗口中看到什么?有没有数据绑定错误?

要调试数据绑定,请参阅 - http://bea.stollnitz.com/blog/index.php?s=presentationtrace