UWP ListView按钮MVVM绑定
问题描述:
我有一个ListView
,现在打开SelectedItem
Popup。 我想要的是,如果用户决定从列表中删除一个项目,他可以单击按钮,它会被删除 - 现在按钮确实会触发,但是如何告诉虚拟机中的按钮要删除的项目 - 没有“的SelectedItem”? PE的UWP ListView按钮MVVM绑定
<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>
VM
public void RemoveXCommand()
{
foreach(var item in pseudo)
{
if(item.Name == ?????)
pseudo.Remove(item);
}
}
有什么办法呢,还是要删除弹出的开放,并执行它作为另一个按钮,这样我就可以使用的SelectedItem得到比较呢?
谢谢。
EDIT1:
感谢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
实现。这里是一个可能的解决方案:(其中i初始化我的命令)(翻译)
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);
}
}
}
如果我试试这个我在构造函数中得到一个错误“的转换,从方法到行动是不可能的),在'RemoveXCommand =新RelayCommand (RemoveXCommandAction)' –
这是因为'RelayCommand'没有实现参数。请看https://*.com/questions/33003207/universal-windows-platform-commanding-with-parameters你需要修改'RelayCommand'通过将对象参数添加到构造函数中的动作 – Fruchtzwerg
所以我必须使用ICommand切换RelayCommand,并且如何在构造函数中添加参数? –