本文介绍了在WPF MVVM +使用Command + CommandParameter在列表视图中删除一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想删除使用Command和CommandParameter像下面的ListView控件中的一行。
< GridViewColumn标题=X>
< GridViewColumn.CellTemplate>
<&DataTemplate的GT;
<&StackPanel的GT;
< TextBlock的文本={结合CriteriaId}/>
<按钮名称=btnDeleteCriterion标签={结合CriteriaId}CONTENT ={结合CriteriaId}前景=红粗细=大胆
命令={结合DeleteCriterionCommand}
的DataContext ={绑定的DataContext,的RelativeSource = {的RelativeSource FindAncestor,AncestorType =的ListView}}
CommandParameter ={绑定的RelativeSource = {自我的RelativeSource},路径=标签}
/>
<&StackPanel的GT;
< / DataTemplate中>
< /GridViewColumn.CellTemplate>
我试图抓住按钮的Tag属性,并把它传递给命令像上面比像这样从列表中删除。
public void DeleteCriterion(object criterionId)
{
int crtId = (int)criterionId;
Criterion crt = _criteria.FirstOrDefault((c) => c.CriterionId == 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
.
这篇关于在WPF MVVM +使用Command + CommandParameter在列表视图中删除一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!