Spandana Jami
Spandana Jami

Reputation: 127

How to bind a button command in wpf style

I am using a style with button in a radgridview header as HeaderCellStyle.Button is placed properly but command is not invoking

Below is my code:

<telerik:GridViewImageColumn Header="" 
                                         Width="30"
                                         ImageHeight="30" 
                                         IsResizable="False" 
                                         DataMemberBinding="{Binding Image}"                                             
                                         HeaderCellStyle="{StaticResource ButtonStyle}"  >
              </telerik:GridViewImageColumn>

Button style:

<Style TargetType="telerik:GridViewHeaderCell" x:Key="ButtonStyle">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="telerik:GridViewHeaderCell">
        <telerik:RadButton x:Name="ClearButton"  Content="{Binding ClearButton,Source={StaticResource FrameworkInfrastructureResources}}"
                           ToolTip="{Binding ClearTooltip,Source={StaticResource FrameworkInfrastructureResources}}"  Margin="5"
                           IsEnabled="True" 
                           HorizontalContentAlignment="Center" 
                           Command="{Binding ClearMessagesCommand}"
        </telerik:RadButton>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

Below is my command in viewmodel:

  public ICommand ClearMessagesCommand { get; set; }
  ClearMessagesCommand = new DelegateCommand(() => { this.Messages.Clear(); });

Upvotes: 4

Views: 1428

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8902

You can use RelativeSource for binding to datacontext of your cell:

<telerik:RadButton x:Name="ClearButton"  Content="{Binding ClearButton,Source={StaticResource FrameworkInfrastructureResources}}"
                       ToolTip="{Binding ClearTooltip,Source={StaticResource FrameworkInfrastructureResources}}"  Margin="5"
                       IsEnabled="True" 
                       HorizontalContentAlignment="Center" 
                       Command="{Binding Path=DataContext.ClearMessagesCommand,,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type telerik:GridViewHeaderCell}}}"
</telerik:RadButton>

There is detailed SO question about RelativeSource. You can also try to bind via ElementName.

Upvotes: 4

Related Questions