Как остановить Label от укладки в wpf - PullRequest
0 голосов
/ 24 февраля 2019

Я создаю программу, в которой при нажатии на кнопку добавляется новый ярлык.Однако проблема в том, что когда вы нажимаете кнопку добавления, метка продолжает складываться поверх друг друга, а не быть списком

Вот код

c #

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace firstwpfapp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        private void addTask(object sender, RoutedEventArgs e)
        {
            String val = input.ToString();
            Label todo = new Label();
            todo.Content = val;
            List.Children.Add(todo);
        }
    }
}

xaml

...
<Window x:Class="firstwpfapp.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:firstwpfapp"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid Margin="-120,-142,0,0" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="0*"/>
            <ColumnDefinition Width="5*"/>
            <ColumnDefinition Width="451*"/>
        </Grid.ColumnDefinitions>
        <StackPanel x:Name="Wrapper"Background="LightGray" Orientation="Horizontal"></StackPanel>
        <TextBox x:Name="input" Grid.Column="2" HorizontalAlignment="Left" Height="31" Margin="106,198,0,0" TextWrapping="Wrap" Text="Enter here" VerticalAlignment="Top" Width="166"/>
        <Button  Content="Button" Grid.Column="2" HorizontalAlignment="Left" Margin="106,234,0,0" VerticalAlignment="Top" Width="166" Height="26" Click="addTask"/>
        <Grid x:Name="List" Grid.Column="2" HorizontalAlignment="Left" Height="391" Margin="507,160,0,0" VerticalAlignment="Top" Width="385"/>
    </Grid>
</Window>

список продолжает накапливаться поверх другого при каждом нажатии кнопки

Ответы [ 3 ]

0 голосов
/ 24 февраля 2019

Заменить сетку

<Grid x:Name="List" Grid.Column="2" HorizontalAlignment="Left" Height="391" Margin="507,160,0,0" VerticalAlignment="Top" Width="385"/>

на StackPanel:

<StackPanel x:Name="List" Grid.Column="2" HorizontalAlignment="Left" Height="391" Margin="507,160,0,0" VerticalAlignment="Top" Width="385"/>

При добавлении дочерних элементов в сетку они накладываются друг на друга (как вы заметили). StackPanel добавляетновые дочерние элементы ниже (или после) предыдущего дочернего элемента.

0 голосов
/ 24 февраля 2019

Попробуйте это ...................

XAML:

 <Grid> 
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <StackPanel VerticalAlignment="Top" HorizontalAlignment="Center"
                Orientation="Horizontal"
                Margin="0,50,0,0">
        <TextBox Name="Input"
                 Width="300"
                 VerticalAlignment="Center"
                 HorizontalAlignment="Left" />
        <Button Name="AddBtn"
                Content="Add"
                Margin="20,0,0,0"
                VerticalAlignment="Center"
                Width="100" 
                Click="AddBtn_Click"/>
    </StackPanel>
    <ListView Name="ItemListView"
              ItemsSource="{Binding Path=LabelItems, Mode=OneWay}"
              Grid.Row="1"
              HorizontalAlignment="Center"
              VerticalAlignment="Top"
              Margin="20"/>
</Grid>

C # код:

 public partial class MainWindow : Window, INotifyPropertyChanged
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private ObservableCollection<string> _labels = new ObservableCollection<string>();

    public ObservableCollection<string> LabelItems
    {
        get { return _labels; }
        set { _labels = value; RaisePropertyChanged(); }
    }

    private void AddBtn_Click(object sender, RoutedEventArgs e)
    {
        if(Input.Text != "" && Input.Text != null)
        {
            LabelItems.Add(Input.Text);
        }
    }


    public event PropertyChangedEventHandler PropertyChanged;

    void RaisePropertyChanged([CallerMemberName]string name = null)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(name));
        }
    }
}
0 голосов
/ 24 февраля 2019

Вы можете пойти дальше и добавить свои элементы в ListView, который будет складывать элементы для вас, а также включать ItemSource, к которому мы можем привязаться, чтобы он создавал строки для каждого нового элемента ToDo для вас:

Примечание: я не проверял ниже;Я на своем Macbook.

  1. Вместо вашего Wrapper StackLayout замените его на:

<ListView Name="Wrapper" Grid.Row="0" Grid.ColumnSpan="3" ItemsSource="{Binding Tasks}" />

Теперь создайте новый файл с именем Task.cs, который мы будем использовать при создании задания нового типа (добавьте приведенное ниже в файл Task.cs):

public class Task { public string task { get; set;} }

Имейте ваше MainWindow наследовать от интерфейса INotifyPropertyChanged INotifyPropertyChanged

public partial class MainWindow : Window, INotifyPropertyChanged

Теперь обновите остальныевашего кода от MainWindow до:

private ObservableCollection<Task> _tasks;
//Tasks will store all of the tasks of type Task that we add to it 
//as well as be bound to our ListView that will display whatever we add to our Tasks
public ObservableCollection<Task> Tasks
{
    get
    {
        return _tasks;
    }

    set
    {
        if (value != _tasks)
        {
            _tasks = value;
            OnPropertyChanged("Tasks");
        }
    }
}
//Here we implement OnPropertyChanged so our ObservableCollection can be notified 
//whenever we have a new task added to or removed from Tasks (this is created when we implement INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string name)
{
    if (PropertyChanged != null)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(name));
    }
}
//Create a new Task and add it to our Tasks any time the addTask button is clicked
private void addTask(object sender, RoutedEventArgs e)
{

    Tasks.Add(new Task(input.Text));
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...