我有一个ListView
,现在打开一个弹出窗口SelectedItem
。我想要的是,如果用户决定从列表中删除一个项目,他可以单击按钮并将其删除 - 现在按钮确实会触发,但是我如何告诉 VM 中的按钮要删除的项目 - 没有“所选项目”?pE。
<ListView
SelectedItem="{Binding...}"
x:Name="lv">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Source="{Binding...}"/>
<Button Command="{Binding ElementName=lv,Path=DataContext.RemoveXCommand}" />
</Stackpanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
虚拟机
public void RemoveXCommand()
{
foreach(var item in pseudo)
{
if(item.Name == ?????)
pseudo.Remove(item);
}
}
有没有办法,或者我是否必须删除Popup的开口,并将其实现为另一个Button,以便我可以使用SelectedItem来进行比较?
谢谢你。
编辑1:
感谢Fruchtzwerg我让它工作了
public RelayCommand<string> RemoveXCommand{ get; private set; }
//... in then Constructor
RemoveXCommand = new RelayCommand<string>((s) => RemoveXCommandAction(s));
public void RemoveXCommand(object temp)
{
foreach(var item in pseudo)
{
if(item.Name == (string) temp)
pseudo.Remove(item);
}
}
您可以将需要删除的项目作为 CommandParameter
<Button Command="{Binding ElementName=lv, Path=DataContext.RemoveXCommand}"
CommandParameter="{Binding}"/>
并删除它
public void RemoveXCommand(object itemToRemove)
{
pseudo.Remove(itemToRemove);
}
您也可以按名称删除项目。Name
将项目的绑定为CommandParameter
<Button Command="{Binding ElementName=lv, Path=DataContext.RemoveXCommand}"
CommandParameter="{Binding Name}"/>
并删除它
public void RemoveXCommand(object nameToRemove)
{
foreach(var item in pseudo)
{
if(item.Name == (string)nameToRemove)
{
pseudo.Remove(item);
}
}
}
请注意,第二种方法是删除具有所选项目名称的所有项目。第一种方法仅删除您选择的项目,因为删除了特定实例。
在RelayCommand
新的或修改的实现中允许参数ICommand
是必需的。这是一个可能的解决方案:
public class ParameterRelayCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<bool> _canExecute;
public event EventHandler CanExecuteChanged;
public ParameterRelayCommand(Action<object> execute)
: this(execute, null)
{ }
public ParameterRelayCommand(Action execute<object>, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句