2

I have the following custom control based on the "heavy option" at this link:

public partial class SelectableContentControl : ContentControl
{
    public SelectableContentControl()
    {
        InitializeComponent();
        var isCheckedDesc = DependencyPropertyDescriptor.FromProperty(IsCheckedProperty, typeof(SelectableContentControl));
        isCheckedDesc.AddValueChanged(this, IsCheckedPropertyChanged);
    }

    public bool IsChecked
    {
        get { return (bool)GetValue(IsCheckedProperty); }
        set { SetValue(IsCheckedProperty, value); }
    }

    public static readonly DependencyProperty IsCheckedProperty =
        DependencyProperty.Register("IsChecked", typeof(bool),
          typeof(SelectableContentControl), new PropertyMetadata(false));

    private void IsCheckedPropertyChanged(object sender, EventArgs e)
    {
        var selectable = Content as IAmSelectable;
        if (selectable != null) selectable.IsSelected = IsChecked;
    }
}

The style defined for the SelectableContentControl is as follows:

<Style TargetType="{x:Type controls1:SelectableContentControl}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type controls1:SelectableContentControl}">
                <CheckBox IsChecked="{TemplateBinding IsChecked}"/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

...and my usage:

<controls:SelectableContentControl Grid.Row="2" Content="{Binding Dummy}" IsChecked="{Binding Dummy.IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

I want IsCheckedPropertyChanged to be called whenever the IsChecked value changes on the UI, but this isn't happening. Anyone see what I'm missing?

ket
  • 728
  • 7
  • 22

1 Answers1

5

TemplateBinding works in a OneWay mode, meaning that the value is updated only in source-to-target direction (your control being the source, and the CheckBox inside the template the target). If you want the binding to work in TwoWay mode, you should use a normal Binding instead:

<ControlTemplate TargetType="{x:Type controls1:SelectableContentControl}">
    <CheckBox IsChecked="{Binding IsChecked, RelativeSource={RelativeSource TemplatedParent}}" />
</ControlTemplate>

Note that you don't need to specify Mode=TwoWay on the binding, because CheckBox.IsChecked property binds in two-way mode by default.

See this question for more detailed info.

Community
  • 1
  • 1
Grx70
  • 10,041
  • 1
  • 40
  • 55
  • 1
    Thanks, that was totally it. The universe would have ended from heat death before I figured that out. – ket Jun 06 '16 at 18:56