Cannot get Two Way Template Binding (WPF) to work

397 views Asked by At

I need help trying to understand why this is not working. According to MSDN, TemplateBinding is what should be used when binding the property of a control in a template to a property of the control implementing the template.

Except that Template Binding is not two-way. For two-way you need to use binding and then specify the relative source as TemplatedParent.

So I have the following XAML: template

<ItemContainerTemplate x:Key="colHeaderTemplate">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding}" VerticalAlignment="Center"/>
                <ToggleButton Style="{StaticResource ToggleButtonStyle}" IsChecked="{Binding RelativeSource={RelativeSource Mode=TemplatedParent}, Mode=TwoWay, Path=(props:VisibilityHelper.IsGroupCollapsed)}"/>
            </StackPanel>
        </ItemContainerTemplate>

which is used here

<dxg:GridColumn x:Name="Total" Header="Total" FieldName="field1" Width="Auto" HorizontalHeaderContentAlignment="Center" props:VisibilityHelper.IsGroupCollapsed="False" HeaderTemplate="{StaticResource colHeaderTemplate}">
                                        <dxg:GridColumn.EditSettings>
                                            <dx:TextEditSettings HorizontalContentAlignment="Center"/>
                                        </dxg:GridColumn.EditSettings>
                                    </dxg:GridColumn>

The toggle button in the template must set a dependency property on the grid column. This works fine when the template is binding to a parent ie. the controls are nested,

I just can't figure out what I am doing wrong.

MSDN ref - http://msdn.microsoft.com/en-us/library/ms742882.aspx

One of the many SO posts about this - In WPF, why doesn't TemplateBinding work where Binding does?

Thank you

1

There are 1 answers

0
dracosveen On

Right so I have found the solution. Firstly DataTemplate does work. As @Quercus, it is all in the binding to the correct control.

In my case not the GridColumn but the GridColumnHeader. So this

IsChecked="{Binding RelativeSource={RelativeSource AncestorType=dxg:GridColumnHeader}, Path=DataContext.(props:VisibilityHelper.IsGroupCollapsed)}"

works perfectly...when bound to the correct parent.

Also as @Quercus stated, the template is actually nested and that is why this works. I used a tool called Snoop which actually shows you the visual tree of the application and then the datacontext of the selected element. Using this I solved this issue as well as 2 others I was having.

I really hope this helps someone somewhere before everyone goes to MAUI or WinUI 3.