Мне нужно удалить элемент управления внутри WrapPanel, созданный динамически внутри другого WrapPanel в то время как во время выполнения - PullRequest
0 голосов
/ 06 января 2020

Итак, у меня есть основной WrapPanel, называемый "valoresPanel". Когда я начинаю работать, мне нужно нажать Button с надписью «2» (ниже), и TextBox должен появиться внутри WrapPanel с надписью «1», который был создан во время выполнения.

this image show how my system looks, it helps to understand

Это мой код для кнопки «+» прямо сейчас:

void novoValor_Click(object sender, RoutedEventArgs e)
       {
           WrapPanel wpValores = new WrapPanel();

           Button deleteValor = new Button();
           TextBox txtValor = new TextBox();

           deleteValor.Height = 25;
           deleteValor.Width = 25;
           deleteValor.Content = "X";

           txtValor.Height = 25;
           txtValor.Width = 70;
           txtValor.Margin = new Thickness(0, 0, 8, 0);

           wpValores.Height = 25;
           wpValores.Width = 105;

           wpValores.Children.Add(deleteValor);
           wpValores.Children.Add(txtValor);

           valoresPanel.Children.Add(wpValores);

           deleteValor.Click += deleteValor2_Click;
       }  

Итак, я обновил свой код, используя только одну WrapPanel на элемент, теперь я могу добавить элемент, добавить значения и удалите элемент с соответствующими значениями, но я не могу удалить значение c, это мой код:

это изображение поможет понять

 void novoValor_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            WrapPanel wpFather = btn.Parent as WrapPanel;
            WrapPanel wpValue = new WrapPanel();

            Button deleteValue = new Button();
            TextBox txtValue = new TextBox();

            wpValue.Height = 25;
            wpValue.Width = 105;

            deleteValue.Height = 25;
            deleteValue.Width = 25;
            deleteValue.Content = "-";

            txtValue.Height = 25;
            txtValue.Width = 70;
            txtValue.Margin = new Thickness(0, 0, 8, 0);

            wpValue.Children.Add(deleteValue);
            wpValue.Children.Add(txtValue);

            wpFather.Children.Add(wpValue);

            deleteValue.Click += deleteValor_Click;
        }

        void deleteValor_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            WrapPanel panel = btn.Parent as WrapPanel;
            entradasPanel.Children.Remove(panel);
        }

Если кому-то нужна какая-либо другая информация, я готов отправить ее как можно быстрее!

Ответы [ 2 ]

1 голос
/ 07 января 2020

Вы должны создать ListView, который имеет WrapPanel как ItemsPanel. Затем к ListView.ItemsSource вы привязываете ObservableCollection моделей данных. Определив DataTemplate для ListView.ItemTemplate, вы можете сделать так, чтобы элементы данных отображались как TextBox с Button, где TextBox связывается с моделью данных этого элемента. Нажав кнопку удаления, вы просто удаляете эту модель данных из ObservaleColection (ItemsSource из ListView).

DataModel.cs

class DataModel
{
  public string UserInput { get; set; }
}

ViewModel.cs

class ViewModel
{
  public ObservableCollection<DataModel> Items { get; set; }
  public ICommand AddItemCommand => new AsyncRelayCommand(() => this.Items.Add(new DataModel()));    
  public ICommand RemoveItemCommand => new AsyncRelayCommand((item) => this.Items.Remove(item));

  public ViewModel()
  {
    this.Items = new ObservableCollection<DataModel>();
  }
}

MainWindow.xaml

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

  <StackPanel>
    <Button Content="Add Item"
            Command="{Binding AddItemCommand}" />

    <ListView ItemsSource="{Binding Items}">
      <ListView.ItemsPanel>
        <ItemsPanelTemplate>
          <WrapPanel Width="600" />
        </ItemsPanelTemplate>
      </ListView.ItemsPanel>

      <ListView.ItemTemplate>
        <DataTemplate DataType="{x:Type DataModel}">
          <StackPanel Orientation="Horizontal">
            <Button Content="Remove Item"
                    Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListView}, Path=DataContext.RemoveItemCommand}"
                    CommandParameter="{Binding}" />
            <TextBox Text="{Binding UserInput}" />
          </StackPanel>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackPanel>
</Window>
0 голосов
/ 07 января 2020

Я мог бы решить мой последний вопрос с помощью следующего кода:

    void deleteValue_Click(object sender, RoutedEventArgs e)
    {
        Button btn = sender as Button;
        WrapPanel panel = btn.Parent as WrapPanel;
        WrapPanel panelPai = panel.Parent as WrapPanel;
        panelPai.Children.Remove(panel);
    }
...