UWP ListView按钮MVVM绑定

时间:2017-05-30 09:12:50

标签: c# listview mvvm uwp

我有一个ListView,现在就在SelectedItem打开一个弹出窗口。 我想要的是,如果用户决定从列表中删除一个项目,他可以单击按钮并将其删除 - 现在Button会触发,但是如何告诉VM中的Button要删除哪个项目 - 没有“的SelectedItem“?体育课..

<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);
       }
    }

有没有办法,或者我是否必须删除Popup的开头,并将其作为另一个Button实现,以便我可以使用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);
   }
}

1 个答案:

答案 0 :(得分:2)

您可以将需要删除的项目传递为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);
        }
    }
}
相关问题