0

Если, через контекстное меню делаю или просто через кнопку работает, но как сделать так чтобы напротив текста был крестик который удалял бы этот самый item хз xaml:

<Window x:Class="NotesTask.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:NotesTask"
        mc:Ignorable="d" 
        xmlns:viewModel="clr-namespace:NotesTask.ViewModel"
    Title=&quot;MainWindow&quot; Height=&quot;450&quot; Width=&quot;800&quot;&gt;

&lt;Window.DataContext&gt;
    &lt;viewModel:NotesViewModel/&gt;
&lt;/Window.DataContext&gt;

&lt;Grid&gt;
    &lt;Grid.RowDefinitions&gt;
        &lt;RowDefinition Height=&quot;28*&quot;/&gt;
        &lt;RowDefinition Height=&quot;3*&quot;/&gt;
    &lt;/Grid.RowDefinitions&gt;

    &lt;ListView ItemsSource=&quot;{Binding Path=NotesModel.Notes}&quot; SelectedItem=&quot;{Binding Path=SelectedNote}&quot; Margin=&quot;10,10,10,10&quot;&gt;
        &lt;ListView.ItemTemplate&gt;
            &lt;DataTemplate x:Name=&quot;NoteTemplate&quot;&gt;
                &lt;StackPanel Orientation=&quot;Horizontal&quot;&gt;
                    &lt;TextBlock Text=&quot;{Binding Path=Title}&quot;  MinHeight=&quot;25&quot; MinWidth=&quot;100&quot; Margin=&quot;3,3,3,3&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Center&quot;/&gt;
                    &lt;Button Command=&quot;{Binding Path=RemoveCommand}&quot; CommandParameter=&quot;{Binding Path=SelectedNote}&quot; Content=&quot;X&quot; MinHeight=&quot;25&quot; MinWidth=&quot;25&quot; Margin=&quot;3,3,3,3&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Center&quot;/&gt;
                &lt;/StackPanel&gt;
            &lt;/DataTemplate&gt;
        &lt;/ListView.ItemTemplate&gt;
        &lt;ListView.ContextMenu&gt;
            &lt;ContextMenu&gt;
                &lt;MenuItem Header=&quot;Delete&quot; Command=&quot;{Binding Path=RemoveCommand}&quot;/&gt;
            &lt;/ContextMenu&gt;
        &lt;/ListView.ContextMenu&gt;
    &lt;/ListView&gt;
    &lt;Button Grid.Row=&quot;1&quot; MinHeight=&quot;25&quot; MinWidth=&quot;50&quot; VerticalAlignment=&quot;Center&quot; HorizontalAlignment=&quot;Center&quot; Content=&quot;Delete&quot; Command=&quot;{Binding RemoveCommand}&quot;/&gt;
&lt;/Grid&gt;

</Window>

ViewModel:

using System;
using System.Windows.Input;

using NotesTask.Model;

namespace NotesTask.ViewModel { internal class NotesViewModel { public Note InputedNote { get; set; }

    public Note SelectedNote { get; set; }

    public NoteModel NotesModel { get; set; } = new NoteModel();

    public ICommand AddCommand { get; set; }

    public ICommand RemoveCommand { get; set; }

    public NotesViewModel()
    {
        AddCommand = new RelayCommand(
            execute =&gt;
            {
                if (InputedNote != null)
                {
                    NotesModel.Add(new Note(InputedNote.Title, InputedNote.Description));
                }
            },

            canExecute =&gt;
            {
                if (InputedNote.Title != &quot;&quot;)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            );

        RemoveCommand = new RelayCommand(
            execute =&gt;
            {
                if (SelectedNote != null)
                {
                    NotesModel.Remove(SelectedNote);
                }
            },

            canExecute =&gt; SelectedNote != null
            );
    }
}

}

aepot
  • 49,560
JoJo
  • 11
  • 4
  • https://ru.stackoverflow.com/a/1116136/373567 – aepot Mar 22 '23 at 12:53
  • @aepot, Если все скопипастить то работает, но почему я не понимаю. Как так получается что кнопки ссылаются на removeCommand, если сам лист прибинден к коллекции в которой нет этой команды?

    И что означает RelativeSource в данных командах: Command="{Binding ItemsSource.DeleteItemCommand, RelativeSource={RelativeSource AncestorType=ListView}}" CommandParameter="{Binding}" ? Правильно понимаю что: RelativeSource= указывает к чему будет привязан объект, а AncestorType=ListView определяет предка кнопки, {RelativeSource AncestorType=ListView} - вызывает сущность к которой привязан предок?

    – JoJo Mar 23 '23 at 13:02
  • Обратите внимание на то как реализована коллекция, обычно в коллекцию не кладут команды, они где-то в обычных вьюмоделях живут или же в элементах коллекции. public class TableOfContentsViewModel : ObservableCollection<TableOfContentsItem> - конечно же так делать не обязательно. Про Ancestor вы верно поняли, что он ищет предка подходящего типа. Можно так к окну обращаться и к главной вьюмодели через DataContext. – aepot Mar 23 '23 at 14:33

0 Answers0