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>
答
您可能需要您的控件的名称设置为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
希望你设置下调试DataContext的 – 2011-04-06 15:15:39
照照输出窗口在Visual Studio中。应该有绑定错误。 – 2011-04-06 15:18:44
其中一个可以通过先了解基础知识轻松解决的问题之一:http://msdn.microsoft.com/en-us/library/ms752347.aspx – 2011-04-06 15:48:04