Поднимите добавление или удаление действия от дочернего, чтобы добавить или удалить элементы в Parent StackPanel - PullRequest
0 голосов
/ 16 марта 2020

Я использую C# и WPF для создания элемента с двумя кнопками: (+) и (-)

Этот элемент является дочерним элементом стековой панели в главном окне.

Мне нужно:

  • Удалить элемент, в котором я щелкнул (-)
  • Добавить еще один элемент в панель стека, когда я нажму (+)

Кто-нибудь может мне помочь с кодом, веб-сайтом, учебником?

Спасибо.

Вот элемент, который я создал в UserControl:

<CheckBox x:Name="cbx_configurationIsActive" Style="{DynamicResource CheckBoxStyle}" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="0"/>
<Button x:Name="btn_Edit" Style="{DynamicResource ButtonEditStyle}" Grid.Row="0" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Button x:Name="btn_Delete" Style="{DynamicResource ButtonPurgeStyle}" Grid.Row="0" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Center"/>
<Label x:Name="Lbl_configName" Content="" Grid.Row="0" Grid.Column="3" Margin="10 0 0 0" HorizontalAlignment="Left" VerticalAlignment="Center"/>

Вот выдержка из окна, где я хотел бы добавить свой элемент:

<ListBox Name="stk_configurationList">
   <ItemsControl ItemsSource="{Binding ConfigurationsList}"/>
</ListBox>

1 Ответ

0 голосов
/ 16 марта 2020

Вы используете ListBox неправильно. ListBox происходит от ItemsControl. Кроме того, вам определенно следует использовать ObservableCollection вместо List в вашем сценарии.

Судя по опубликованному коду, вам следует прочитать некоторые фундаментальные знания (я не проверял качество связанного содержимого, но я обычно рекомендую все источники Microsoft):

Простой пример того, как добавлять / удалять элементы в / из коллекции, вызываемые кнопками:

Configuration.cs

class Configuration
{  
  public string TextValue { get; set; }
}

ViewModel.cs
(См. Документы Microsoft: Шаблоны - Приложения WPF с моделью. Шаблон проектирования View-ViewModel для примера реализации RelayCommand )

class ViewModel
{
  public ObservableCollection<Configuration> Configurations { get; set; }
  public ICommand DeletedItemCommand => new RelayCommand(ExecuteDeleteItem, CanExecuteDeleteItem);
  public ICommand AddItemCommand => new RelayCommand(ExecuteAddItem);

  public ViewModel()
  {
    this.Configurations = new ObservableCollection<Configuration>() 
    {
      new Configuration() {TextValue = "Initial Item"}
    };
  }

  private void CanExecuteDeleteItem(object commandParameter) => commandParameter is Configuration && this.Configurations.Any();

  private void ExecuteDeleteItem(object commandParameter) => this.Configurations.Remove(commandParameter as Configuration);

  private void ExecuteAddItem(object commandParameter) => this.Configurations.Add(new Configuration() {TextValue = "Some Text"});
}

MainWindow.xaml

<Window>
  <Window.DataContext>
    <ViewModel />
  </Window.DataContext>

  <StackPanel>
    <Button Content="Add Item" Command="{Binding AddItemCommand}" />
    <ListBox ItemsSource="{Binding Configurations}">
      <ListBox.ItemTermplate>
        <DataTemplate DataType="{x:Type Configuration}">
          <StackPanel Orientation="Horizontal">
            <TextBlock="{Binding TextValue}" />
            <Button Content="x" Command="{Binding DeleteItemCommand}" />
          </StackPanel>
        </DataTemplate>
      </ListBox.ItemTermplate>
    </ListBox>
  </StackPanel>
</Window>
...