I have a simple User Control
Xaml:
<UserControl x:Class="GraemeGorman_Controls.Navigation.NavigationItem"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Border x:Name="borderLayoutRoot">
<TextBlock x:Name="textBlockCaption" Text="{Binding Caption}" />
</Border>
</UserControl>
Cs:
namespace GraemeGorman_Controls.Navigation
{
public partial class NavigationItem : UserControl
{
public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register(
"Caption",
typeof (string),
typeof (NavigationItem),
new PropertyMetadata(new PropertyChangedCallback(OnCaptionChanged)));
public string Caption
{
get {return (string)GetValue(CaptionProperty);}
set {SetValue(CaptionProperty, value);}
}
public NavigationItem()
{
InitializeComponent();
}
private static void OnCaptionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
//null
}
}
}
What my issue is, when I create an instance of the control the caption never shows - now i have tested the property in the OnCaptionChanged function using e.NewValue and it is the correct value开发者_JAVA百科. What is wrong with my binding?
If I write in the code behind caption property for set
textBlockCaption.Text = value;
It appears fine...
Any help appreciated
Thanks Graeme
From the code-behind it looks like you are missing one line of code.
Try to add DataContext = this;
in your constructor. This has worked for me in the past.
How are you creating the instance of the NavigationItem control?
you'll need to do something like:
<Page ...
xmlns:gg="clr-namespace:GraemeGorman_Controls.Navigation">
<gg:NavigationItem Caption="FooBar" />
or even
<gg:NavigationItem Caption="{Binding Path=TheCaption}" />
where TheCaption is a property of your Page's DataContext (eg your ViewModel)
Hope This Helps :)
精彩评论