Как заполнять список с информацией формы каждый раз, когда нажимается кнопка «зарегистрироваться» (без BD) - PullRequest
0 голосов
/ 05 июня 2019

Я хочу, чтобы при нажатии на кнопку «Регистрация» немедленно отображалось в listBox ранее введенная информация и, таким образом, число новых записей было равно «n».

Я не использую BD , я использую Newtonsoft.Json для сохранения данных формы.Но я хочу, чтобы каждый serializeObject был новой записью, представленной в listBox.Я работаю над файлом MainPage.xaml.cs .

Я новичок в c # и POO , как я могу это сделать?Я ценю вашу помощь.Это я продвинулся:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
    }

    private async void RegistrerDebtor(object sender, RoutedEventArgs e)
    {            
        Person person = new Person();
        person.Identification = TxtIdentification.Text;
        person.Name = TxtName.Text;
        person.LastName = TxtLastName.Text;
        person.Address = TxtAddress.Text;
        person.Phone = TxtPhone.Text;
        person.Email = TxtMail.Text;
        person.Latitude = TxtLatitude.Text;
        person.OriLat = CbxOrientationLat.Text;
        person.Longitude = TxtLongitude.Text;
        person.OriLon = CbxOrientationLon.Text;
        string json = JsonConvert.SerializeObject(person, Formatting.Indented);

        MessageDialog msgdialog = new MessageDialog(Convert.ToString(json), "Titulo dialogo");
        await msgdialog.ShowAsync();
    }
}
public class Person
{
    public string Identification { get; set; }
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Phone { get; set; }
    public string Email { get; set; }
    public string Latitude { get; set; }
    public string OriLat { get; set; }
    public string Longitude { get; set; }
    public string OriLon { get; set; }
}

<StackPanel>
    <TextBox x:Name="TxtIdentification"></TextBox>
    <TextBox x:Name="TxtName"></TextBox>
    <TextBox x:Name="TxtLastName"></TextBox>
    <TextBox x:Name="TxtAddress"></TextBox>
    <TextBox x:Name="TxtPhone"></TextBox>
    ....
    ....
    ....
    <Button Content="Register" Click="RegistrerDebtor"></Button>
</StackPanel>

1 Ответ

2 голосов
/ 05 июня 2019

Установите или привяжите ItemsSource ListBox к ObservableCollection<Person> и добавьте объект Person к этому объекту в обработчике события щелчка:

public sealed partial class MainPage : Page
{
    private readonly ObservableCollection<Person> _persons = new ObservableCollection<Person>();

    public MainPage()
    {
        this.InitializeComponent();
        listBox.ItemsSource = _persons;
    }

    private void RegistrerDebtor(object sender, RoutedEventArgs e)
    {
        Person person = new Person();
        person.Identification = TxtIdentification.Text;
        person.Name = TxtName.Text;
        person.LastName = TxtLastName.Text;
        person.Address = TxtAddress.Text;
        person.Phone = TxtPhone.Text;
        person.Email = TxtMail.Text;
        person.Latitude = TxtLatitude.Text;
        person.OriLat = CbxOrientationLat.Text;
        person.Longitude = TxtLongitude.Text;
        person.OriLon = CbxOrientationLon.Text;

        _persons.Add(person);
    }
}

Затем можно использоватьItemTemplate для определения внешнего вида каждого Person:

<ListBox x:Name="listBox">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                <TextBlock Text="{Binding LastName}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Если вы хотите отобразить сериализованную строку в ListBox, вы можете просто изменить тип исходной коллекции и добавить strings к нему вместо Person объектов:

public sealed partial class MainPage : Page
{
    private readonly ObservableCollection<string> _persons = new ObservableCollection<string>();

    public MainPage()
    {
        this.InitializeComponent();
        listBox.ItemsSource = _persons;
    }

    private void RegistrerDebtor(object sender, RoutedEventArgs e)
    {
        Person person = new Person();
        person.Identification = TxtIdentification.Text;
        person.Name = TxtName.Text;
        person.LastName = TxtLastName.Text;
        person.Address = TxtAddress.Text;
        person.Phone = TxtPhone.Text;
        person.Email = TxtMail.Text;
        person.Latitude = TxtLatitude.Text;
        person.OriLat = CbxOrientationLat.Text;
        person.Longitude = TxtLongitude.Text;
        person.OriLon = CbxOrientationLon.Text;
        string json = JsonConvert.SerializeObject(person, Formatting.Indented);
        _persons.Add(json);

    }
}

Тогда вам не понадобится ItemTemplate.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...