简体   繁体   English

ListBox不刷新?

[英]ListBox doesn't refresh?

i have an issue on Visual Studio(wpf) with the listbox. 我在使用列表框的Visual Studio(wpf)上遇到了问题。 If i want to insert or delete some data from the database, then they are working,but the listbox will just be refreshed if i'm clicking the menuitem for once. 如果我想从数据库插入或删除一些数据,那么它们正在工作,但如果我点击menuitem一次,列表框将会刷新。 I think this is due to the load method, but why isn't it refreshing the data? 我认为这是由于加载方法,但为什么不刷新数据呢?

This is my XAML-Code: 这是我的XAML代码:

  <UserControl x:Class="WpfApplication1.AutorenBearbeiten"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WpfApplication1"
             mc:Ignorable="d" 
             d:DesignHeight="400" d:DesignWidth="300" Loaded="UserControl_Loaded">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="28*" />
            <ColumnDefinition Width="36*" />
        </Grid.ColumnDefinitions>
        <TextBlock Text="Medien" Grid.ColumnSpan="2" 
                   FontSize="16" />





        <ListBox x:Name="box" Grid.Row="1">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Path=at_nachname}" />



                </DataTemplate>

            </ListBox.ItemTemplate>
        </ListBox>

        <StackPanel DataContext="{Binding ElementName=box,Path=SelectedItem}" Grid.Column="1" Grid.Row="1" >
            <TextBlock Text="Autoren_id" />
            <TextBox  Text="{Binding Path=at_id}"  MaxLength="5"/>
            <TextBlock Text="Vorname"  />
            <TextBox   Text="{Binding Path=at_vorname}"   MaxLength="30"/>
            <TextBlock Text="Nachname" />
            <TextBox  Text="{Binding Path=at_nachname}"  MaxLength="30"/>
            <TextBlock Text="Geburtsdatum"  />
            <TextBox   MaxLength="30"  Text="{Binding Path=at_gebDatum, StringFormat=dd.MM.yyyy}" />
            <Button Name="speichern" Height="23" Margin="4" Click="speichern_Click">Änderungen speichern</Button>
            <Button Name="loeschen" Height="23" Margin="4" Click="loeschen_Click">Löschen</Button>

            <StackPanel DataContext="{Binding ElementName=box}" Grid.Column="1" Grid.Row="1" >
                <TextBlock Text="Autoren_id" />
                <TextBox x:Name="id"  MaxLength="5"/>
                <TextBlock Text="Vorname" />
                <TextBox  x:Name="vorname"   MaxLength="30"/>
                <TextBlock Text="Nachname" />
                <TextBox x:Name="nachname"   MaxLength="30"/>
                <TextBlock Text="Geburtsdatum" />
                <TextBox  x:Name="datum" MaxLength="30"/>
                <Button x:Name="neubutton"  Height="23" Margin="4" Click="neu_Click">Neu</Button>
                <TextBlock Name="submitfehler" FontWeight="Bold" Foreground="Red" />
            </StackPanel>

        </StackPanel>

    </Grid>
</UserControl>

And this is the xaml.cs file : 这是xaml.cs文件:

    using System;
using System.Collections.Generic;
using System.Data.Entity;
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 WpfApplication1
{
    /// <summary>
    /// Interaction logic for AutorenBearbeiten.xaml
    /// </summary>
    public partial class AutorenBearbeiten : UserControl
    {
        libraryEntities6 db = new libraryEntities6();
        public AutorenBearbeiten()
        {
            InitializeComponent();
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            var erg = db.a_autor;

            erg.Load();
            box.ItemsSource = erg.Local.OrderBy(m => m.at_id);

            box.ItemsSource =
               (from m in db.a_autor
                orderby m.at_id
                select m).ToList();


    }

        private void speichern_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                db.SaveChanges();
            }
            catch(Exception e1)
            {
                submitfehler.Text = e1.Message;
            }
        }

        private void loeschen_Click(object sender, RoutedEventArgs e)
        {

            a_autor am = (a_autor)box.SelectedItem;
            if (am != null)
            {

                db.a_autor.Remove(am);
                db.SaveChanges();
                box.Items.Refresh();
            }

        }

        private void neu_Click(object sender, RoutedEventArgs e)
        {


            a_autor autor = new a_autor();
            autor.at_id = id.Text;
            autor.at_vorname = vorname.Text;
            autor.at_nachname = nachname.Text;
            autor.at_gebDatum = Convert.ToDateTime(datum.Text);


            //s1.s_k_klasse = liklassen.SelectedValue.ToString() setzt die Klasse via foreign key
            //db.schuelers.AddObject(s1);


            db.a_autor.Add(autor);
            box.Items.Refresh();



            /*
            ((klassen))liklassen.SelectedItem).schuelers.Add(s1); //setzt die klasse durch zuweisen zum nav.Property
            lischueler.Items.Refresh(); //nötig weil das navigational seit ER 5 nicht observable ist
            */

        }
    }
}

A Picture from the window is below: 窗口中的图片如下:

Window 窗口

You should use MVVM pattern instead of code behind and use property changes. 您应该使用MVVM模式而不是代码隐藏并使用属性更改。 First result in Google: 谷歌的第一个结果:

https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level https://www.codeproject.com/Articles/819294/WPF-MVVM-step-by-step-Basics-to-Advance-Level

I hope it helps you. 我希望它对你有所帮助。

Juan 胡安

You can create an ObservableCollection instead of binding to the List . 您可以创建ObservableCollection而不是绑定到List ObservableCollection implements INotifyPropertyChanged so it can send a notification whenever something is changed in the container. ObservableCollection实现了INotifyPropertyChanged因此它可以在容器中发生更改时发送通知。

Also, I would suggest you to try 另外,我建议你试试

public void RefreshListBox()
{
     box.ItemsSource =
               (from m in db.a_autor
                orderby m.at_id
                select m).ToList();

}

and call this after db.SaveChanges() 并在db.SaveChanges()之后调用它

There is no magic connection between the ListBox and the database so when you are calling the Add or Remove method of the DbContext the ListBox won't be affected. ListBox和数据库之间没有神奇的连接,因此当您调用DbContext的Add或Remove方法时,ListBox不会受到影响。

What you should do is to set the ItemsSource property of the ListBox to an ObservableCollection<a_autor> and then call the Add/Remove method of this one besides calling the Add/Remove method of the DbContext: 你应该做的是将ListBox的ItemsSource属性设置为ObservableCollection<a_autor> ,然后调用此方法的Add / Remove方法,同时调用DbContext的Add / Remove方法:

System.Collections.ObjectModel.ObservableCollection<a_autor> _sourceCollection;
private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    var erg = db.a_autor;
    erg.Load();

    _sourceCollection = new System.Collections.ObjectModel.ObservableCollection<a_autor>((from m in db.a_autor
                                                                                          orderby m.at_id
                                                                                          select m).ToList());
    box.ItemsSource = _sourceCollection;
}

private void loeschen_Click(object sender, RoutedEventArgs e)
{
    a_autor am = (a_autor)box.SelectedItem;
    if (am != null)
    {
        _sourceCollection.Remove(am);
        db.a_autor.Remove(am);
        db.SaveChanges();
        box.Items.Refresh();
    }

}

private void neu_Click(object sender, RoutedEventArgs e)
{
    a_autor autor = new a_autor();
    autor.at_id = id.Text;
    autor.at_vorname = vorname.Text;
    autor.at_nachname = nachname.Text;
    autor.at_gebDatum = Convert.ToDateTime(datum.Text);

    _sourceCollection.Add(autor);
    db.a_autor.Add(autor);
    box.Items.Refresh();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM