在RelayCommand中,对象发送者始终为null [英] object sender is always null in RelayCommand

查看:92
本文介绍了在RelayCommand中,对象发送者始终为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用RelayCommand处理按钮单击,我需要获取sender参数,但是它始终为null,知道为什么吗?

I am using RelayCommand to handle a button click, I need to get the sender parameter but it is always null, any idea why?

ViewModel.cs

ViewModel.cs

    private RelayCommand _expandClickCommand;
    public ICommand ExpandClickCommand
    {
        get
        {
            if (_expandClickCommand == null)
            {
                _expandClickCommand = new RelayCommand(ExpandClickCommandExecute, ExpandClickCommandCanExecute);
            }
            return _expandClickCommand;
        }
    }

    public void ExpandClickCommandExecute(object sender)
    {
        //sender is always null when i get here! 
    }
    public bool ExpandClickCommandCanExecute(object sender)
    {
        return true;
    }

View.xaml

View.xaml

<ListBox ItemsSource="{Binding Path=MyList}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

                <Button Grid.Column="0" Grid.Row="0" Content="Expand" Command="{Binding DataContext.ExpandClickCommand,ElementName=SprintBacklog}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我需要在ExpandClickCommand中获取当前ListboxItem的索引

I need to get the index of the currect ListboxItem in ExpandClickCommand

推荐答案

该对象很可能不是发件人,而是控件传递的CommandParameter.您可以将按钮的CommandParameter绑定到自身以模仿sender.

That object in all likelihood is not the sender but the CommandParameter that is passed by the control. You could bind the CommandParameter of the button to itself to immitate the sender.

CommandParameter="{Binding RelativeSource={RelativeSource Self}}"

(但这可能对您没有太大帮助,所以请考虑您传递的内容可以帮助您获得该价值.)

这篇关于在RelayCommand中,对象发送者始终为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆