0

My custom control wont work when I have it bound like this (The text block displays my view model property Test fine, but my custom control displays the default value empty):

<local:DynamicMenu Text="{Binding Test}"/>
<TextBlock Text="{Binding Test}"></TextBlock>

If I have a static value it does work though:

<local:DynamicMenu Text="test"/>
<TextBlock Text="{Binding Test}"></TextBlock>

It is implemented as such. I would prefer a solution that would make it work like the TextBlock.

.Xaml.CS

public partial class DynamicMenu : UserControl
{
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text",
            typeof(string),
            typeof(DynamicMenu),
            new FrameworkPropertyMetadata("Empty",
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

    public DynamicMenu()
    {
        InitializeComponent();
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

}

.Xaml

<UserControl x:Class="Whelen.Griffin.Views.DynamicMenu"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" 
             DataContext="{Binding RelativeSource={RelativeSource Self}}" >
    <TextBlock Text="{Binding Text}"></TextBlock>
</UserControl>

1 Answers1

1

This is your problem:

         DataContext="{Binding RelativeSource={RelativeSource Self}}" >

The binding in the parent XAML looks for a property named Test on the DynamicMenu's DataContext. That should be the viewmodel, but unfortunately you set its DataContext to itself, and it has no property named Test.

Don't ever set a UserControl's DataContext to this. That's a classic error.

Delete that line setting the DataContext, and do this instead:

<TextBlock 
    Text="{Binding Text, RelativeSource={RelativeSource AncestorType=UserControl}}" 
    />