簡體   English   中英

UWP ListView按鈕MVVM綁定

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM