XAML: Bind to a property of a custom control from a Template

123 Views Asked by At

in my WPF app I have a custom control with a dependency object

public static readonly DependencyProperty SomeFieldProperty =
            DependencyProperty.Register("SomeField", typeof(double), typeof(MyControl), new PropertyMetadata((double)0, OnPropChanged));

public double SomeField
{
    get { return (double)GetValue(SomeFieldProperty ); }
    set { SetValue(SomeFieldProperty , value); }
}

And from my XAML I'm trying to bind to SomeField like below but it doesn't work: UPDATED:

<UserControl.Template>
    <ControlTemplate TargetType="ContentControl">
        <WrapPannel >
            <abc:MyControl SomeField="{Binding SomeValue, Mode=TwoWay}" />
        </WrapPannel>
    </ControlTemplate>
</UserControl.Template>

Tried different solutions suggested in this like questions in the StackOverflow but none of them worked. Maybe my case is a specific one as I am trying to bind from within a template?

1

There are 1 best solutions below

5
On

Looks like it is not a binding problem. Actually the Template property of a UserControl is overrideb by InitializeComponent(). Something like this will work:

<UserControl x:Class="WPF.MyUserControl"
             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:WPF"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <WrapPannel>
        <abc:MyControl SomeField="{Binding SomeValue, Mode=TwoWay}" />
    </WrapPannel>
</UserControl>

Actually UserControls are to be used when Templates are not needed. Otherwise use Controls, ContentControls or ItemsControls.