【问题标题】:WPF Binding to plain property - not workingWPF绑定到普通属性 - 不起作用
【发布时间】:2011-04-06 15:10:45
【问题描述】:

我有一个控件,我想在它自己的类中将颜色绑定到普通属性。

但它无法工作???有什么线索吗?

我有这个

 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>

【问题讨论】:

标签: .net wpf xaml binding


【解决方案1】:

ElementName=容器

暗示您正在绑定到另一个名为“容器”的 XAML 元素,您可能希望使用“SeperatorColour”属性绑定到对象的某个实例。

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

【讨论】:

  • 我已经删除了“ElementName” - 仍然没有乐趣
  • 我需要以某种方式将数据绑定设置为“this”吗?
  • 数据上下文在这里很重要。
  • 默认情况下,数据上下文是'this'。您可以使用 object.DataContext = otherObject; 从代码隐藏设置数据上下文,也可以使用 Datacontext="otherObject" 从 XAML(引用另一个 XAML 对象)设置数据上下文
【解决方案2】:

您需要将控件的名称设置为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}"

【讨论】:

    【解决方案3】:

    如果您为 UserControl 正确设置了 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

    【讨论】:

      最近更新 更多