开发者

Deleting row in listview using Command + CommandParameter in WPF + MVVM

开发者 https://www.devze.com 2023-03-25 23:40 出处:网络
I want to delete a row in ListView Control using Command and CommandParameter like below. <GridViewColumn Header=\"X\">

I want to delete a row in ListView Control using Command and CommandParameter like below.

<GridViewColumn Header="X">
<GridViewColumn.CellTemplate>
    <DataTemplate>
        <StackPanel>
           <TextBlock Text="{Binding CriteriaId}"/>
           <Button Name="btnDeleteCriterion" Tag="{Binding CriteriaId}" Content="{Binding CriteriaId}" Foreground="Red" FontWeight="Bold" 
                                                             Command="{Binding DeleteCriterionCommand}" 
                                                                        DataContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}}"
                                                             CommandParameter="{Binding RelativeSource={RelativeSource self}, Path=Tag}"
                                                                        />
        <StackPanel>
    </DataTemplate>
</GridViewColumn.CellTemplate>

I am trying to grab the Tag property of the Button and pass it to Command like above and than remove it from list like so.

Edited, above XAML and added a TextBlock which uses the same binding as the Button's Tag and Content, but somehow Button doesn't get the value but TextBlock does!?

    public void DeleteCriterion(object criterionId)
    {
        int crtId = (int)criterionId;
        Criterion crt = _criteria.FirstOrDefault((c) => c.Crite开发者_高级运维rionId == crtId);
        if (crt != null)
            _criteria.Remove(crt);
    }

but I always get criterionId parameter as null.

What am I doing wrong?


Since you're explicitly setting the DataContext within the button, when you're doing a binding like {Binding SomeProperty} it will assume that SomeProperty is in the DataContext that you just set. Try using a more explicit binding like:

"{Binding RelativeSource={RelativeSource AncestorType=StackPanel}, Path=DataContext.CriteriaId}" 

which will give you the correct DataContext's CriteriaID like it is for the TextBlock.


As long as your button's Tag isn't null (if it is null, you have a different problem), I don't see a reason that you can't bind directly to CriterionId like you do with Tag.

0

精彩评论

暂无评论...
验证码 换一张
取 消