Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding Commands to Button Inside ItemTemplate

Hello I am trying to bind a command to a button inside a LongListSelector's ItemTemplate. But facing binding problems. Here are my codes-

XAML

<DataTemplate x:Key="ItemTemplate">
        <StackPanel Height="108" Width="308" Margin="6,6">
            <TextBlock Text="{Binding Name}" Foreground="red"></TextBlock>
            <TextBlock Text="{Binding Type}" Foreground="red"></TextBlock>
            <Button Content="add to emergency" Foreground="White" Background="red" Command="{Binding Path=DataContext.MyViewModelCommand}"/>
        </StackPanel>
    </DataTemplate>

Command

public class ActionCommand : ICommand
{
    private readonly Action _action;

    public ActionCommand(Action action)
    {
        _action = action;
    }

    public void Execute(object parameter)
    {
        _action();
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

ViewModel

public class HspitalVM:INotifyPropertyChanged
{
    public HspitalVM()
    {
        MyViewModelCommand = new ActionCommand(DoSomething);
    }

    public ICommand MyViewModelCommand { get; private set; }
    private void DoSomething()
    {

    }
}

The command works okay for bare buttons, but doesn't work inside ItemTemplate. Please guide me

like image 902
Lamia Mehreen Avatar asked Apr 08 '26 06:04

Lamia Mehreen


1 Answers

Mostly its because the button gets bound to the item DataContext and not your ViewModel DataContext you should modify your command binding to somthing like the following :

Command="{Binding Path=DataContext.MyViewModelCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}

The x:Type shall be the parent type that your ViewModel DataContext is set to, it can be Page or a UserControl or any Container, basicly the Control that has your ViewModel DataContext.

And your command has to have a parameter since you will be acting on the item itself, just like the following

 CommandParameter="{Binding}"

This means that the command paramer is the item that the button was clicked on in your View, you can react on it in the ViewModel by adding its reference to another List or removing it, depending on what you want to do.

like image 125
FPGA Avatar answered Apr 11 '26 08:04

FPGA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!