I have a control where I want to bind a colour to plain property in its own class.
But it fails to work ??? any Clues ?
I have this
public Brush SeperatorColour
{
get { return (Brush)GetValue(SeperatorColourProperty); }开发者_JAVA技巧
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));
And this
<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>
ElementName=container
implies that you are binding to another XAML element named 'container', you will probably want to bind to some instance of the object with the 'SeperatorColour' property.
If you're not binding to another XAML element, do not add "ElementName" to the binding expression.
You either need to set the name of your control to container
:
<UserControl xmlns="..."
x:Name="container">
OR use relative binding:
Fill="{Binding Path=SeperatorColour, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MyControl}}, Mode=OneTime}"
Here, instead of MyControl
you need to specify type of your control.
In case if it is a custom control and the XAML you've shown is located inside a control template for the control, then you can use TemplateBinding
:
Fill="{TemplateBinding SeperatorColour}"
This should work perfectly, if you have correctly set the DataContext for your UserControl -
<Rectangle Name="MessageSeperator" Height="auto" Width="10" Fill="{Binding Path=SeperatorColour, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" />
What do you see in Output window on running you application? Was there any data binding error??
To debug your data bindings, please refer - http://bea.stollnitz.com/blog/index.php?s=presentationtrace
精彩评论