命令绑定不起作用如果一个列表框的项目模板内 [英] Command binding doesn't function if its inside an item template of a listbox

查看:175
本文介绍了命令绑定不起作用如果一个列表框的项目模板内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的用户控件

<ListBox   ItemsSource="{Binding Persons}" 
           SelectedItem="{Binding SelectedPerson}" 
           VerticalAlignment="Top" Width="166" >
            <ListBox.Template>
                <ControlTemplate>
                    <StackPanel >
                        <ItemsPresenter/>
                        <Button Content="Add" Background="Transparent" Command="{Binding NewItemCommand}"/>
                    </StackPanel>
                </ControlTemplate>
            </ListBox.Template>

            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Button  Height="16" Width="16" Background="Transparent" Command="{Binding DeleteItemCommand}">
                            <Image Source="images/delete-icon.png" />
                        </Button>
                        <TextBlock Text="{Binding Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

和我有这两个命令,第一个命令,你可以在上面看到一个视图模型 NewItemCommand 工作正常,第二个命令 DeleteItemCommand 怎么过不起作用。

and i have a view model for it with two commands, the first command that you can see above NewItemCommand is working fine, how ever the second command DeleteItemCommand doesn't function.

是不是因为其在项目模板?

is it because its in the item template?

推荐答案

是的,这是因为的DataContext 的ItemTemplate 不是<$ C $的项目C>视图模型

Yes, this is because the DataContext for the ItemTemplate is the Item from Persons not the ViewModel

要绑定 DeleteItemCommand 每个你将需要绑定物品回视图模型持有该命令

To bind the DeleteItemCommand on each item you will need to bind back to the ViewModel that is holding the command

为例,结合到的DataContext 的ListBox

<Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}" />






编辑:



如果您要删除的项目,该按钮被点击,你可以在通过按钮所属的项目作为 CommandParameter 并处理您的comman,不知道是什么类型的您正在使用的命令,但是这个,如果你使用的是简单的 RelayCommand DelegateCommand


If you want to remove the item that the button was clicked on you can pass the item the button belongs to as the CommandParameter and handle that in your comman, Not sure what type of command you are using but this is simple if you are using RelayCommand or DelegateCommand

 <Button Command="{Binding Path=DataContext.DeleteItemCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}}"
         CommandParameter="{Binding}" />

public MainWindow()
{
    InitializeComponent();
    DeleteItemCommand = new RelayCommand(person => DeletePerson(person as Person));
}

private void DeletePerson(Person person)
{
    Collection.Remove(person);
}

这篇关于命令绑定不起作用如果一个列表框的项目模板内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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