0
votes

Suppose I have a UserControl which has a DataContext set to it's VM

Now suppose the UserControl has a dependency property defined that I want to initially bind to a property on the ViewModel ...how would I reference this property in the XAML of the UserControl given the top-level element is UserControl?

<UserControl x:Class="TestApp1.TestControl"
         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" 
         xmlns:local="clr-namespace:TestApp1"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" x:Name="test">

</UserControl>

Dependency property:

    public static readonly DependencyProperty MyTestPropProperty= null;

    public string MyTestProp
    {
        get { return (string)GetValue(MyTestPropProperty); }
        set { SetValue(MyTestPropProperty, value); }
    }

    static TestControl()
    {
        MyTestPropProperty= DependencyProperty.Register(
            "MyTestProp",
            typeof(string), 
            typeof(TestControl), 
            new FrameworkPropertyMetadata());
    }

On the XAML I"d like to be able go MyTestProp={Binding yadda yadda} but I have no way to reference it from XAML

1

1 Answers

0
votes

Just add the property in the root node like so:

<Usercontrol xmlns=blablabla MyProperty="{Binding MyViewModelProperty}">

Edit: This doesn't work because there is no XAML reference to the newly created property. Either use a <Style TargetType="TestControl"> or set the property from an outer context (the one that contains this usercontrol)