How to bind a command to WPF XAML button from Data template.

Introduction

This post will help you in binding a command to a button, where the button is defined in a template say a data template. With normal command binding it won’t work. We need some sort of workaround to achieve this.

How to fix this.

Here the requirement is to bind a command to an element which is defined in a template. When we do a normal command binding, it is not aware of the data context and will not resolve. We need to provide the binding with the data context. This can be achieved in many ways say you can do

<Button Content="{Binding}" Command="{Binding RelativeSource={RelativeSource Window}, Path=DataContext.ClickHandlerCommand }" />
<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, Source={StaticResource MainWindow}}" />
<Button Content="{Binding}" Command="{Binding Path= ClickHandlerCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

But these won’t work with all scenarios. But one solution will work with all scenarios. Define your data context as a static resource and refer it as the source of the binding. As shown below.

<Window []
        xmlns:this="clr-namespace:Your.Namespace.For.The.ViewModel"
        []>

    <Window.Resources>
        <this:MainWindowViewModel x:Key="Model" />

        <DataTemplate x:Key="ItemsDataTemplate">
          <Button Content="{Binding }" Command="{Binding Command, Source=                            {StaticResource Model}}" />
        </DataTemplate>

    </Window.Resources>

    <Window.DataContext>
        <this:MainWindowViewModel></this:MainWindowViewModel>
    </Window.DataContext>

        <Grid>
        <ItemsControl ItemTemplate="{DynamicResource ItemsDataTemplate"  ItemsSource="{Binding Collections, Mode=OneTime}" >
            
        </ItemsControl>
    </Grid>
</Window>

Setting Up Kafka

Apache Kafka is a high-throughput, low-latency event processing system designed to handle millions of data feeds per second. It has the c...… Continue reading

Libish Varghese Jacob

Libish Varghese JacobI am a lead engineer at a prominent wind turbine manufacturing firm. My interests span a diverse range, and immersing myself in technology is one of them. This platform serves as my primary knowledge base, where I seek information and insights. Moreover, I utilize this platform to share my experiences and experiments, hoping they may benefit those following a similar path. It's important to note that the suggestions I express here are based on my best knowledge at the time of writing and may not necessarily represent the optimal solutions. I wholeheartedly welcome any comments you may have to improve or refine my ideas. Your feedback is greatly appreciated and valued.