C# – Silverlight UserControl Binding

bindingcsilverlightuser-controlswpf

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. 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

Best Answer

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.

Related Topic