[英]UWP ListView Button MVVM Binding
我有一个ListView
,现在在SelectedItem
上打开一个Popup。 我想要的是,如果用户决定从列表中删除某个项目,他可以单击按钮并将其删除-现在按钮确实会触发,但是我如何告诉VM中的按钮要删除的项目-不带“ SelectedItem”? E
<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
使用参数, 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.