如何在WPF中添加或删除项目时自动刷新列表框?

时间:2016-09-14 11:23:46

标签: wpf web-services

我有使用Web服务(asmx)的WPF应用程序。 Web服务使用EF从MS SQL Server获取数据。

代码如下:

1)WPF:

public partial class MainWindow : Window
{
    LetterWebServiceSoapClient _client = new LetterWebServiceSoapClient();
    private ObservableCollection<Letter> _letters;

    public MainWindow()
    {
        InitializeComponent();
    }

    private void cmdGetLetters_Click(object sender, RoutedEventArgs e)
    {
        lstLetters.ItemsSource = null;
        _letters = _client.GetAllLetters();
        lstLetters.ItemsSource = _letters;
    }

    private void cmdDeleteLetter_Click(object sender, RoutedEventArgs e)
    {
        _client.DeleteLetter((Letter)lstLetters.SelectedItem);
    }

    private void cmdAddLetter_Click(object sender, RoutedEventArgs e)
    {
        var newLetter = new Letter
        {
            Name = "Letter3",
            Date = DateTime.Now,
            Recipient = "John",
            Sender = "David",
            Content = "cccc"
        };
        _client.AddNewLetter(newLetter);
    }
}

2)网络服务:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
// [System.Web.Script.Services.ScriptService]
public class LetterWebService : System.Web.Services.WebService
{
    LetterDbEntities _letterDbEntities = new LetterDbEntities();

    [WebMethod]
    public ObservableCollection<Letter> GetAllLetters()
    {
        return new ObservableCollection<Letter>(_letterDbEntities.Letters.ToList());
    }

    [WebMethod]
    public void AddNewLetter(Letter newLetter)
    {
        _letterDbEntities.Letters.Add(newLetter);
        _letterDbEntities.SaveChanges();
    }

    [WebMethod]
    public void DeleteLetter(Letter letter)
    {
        var letterToBeDeleted = _letterDbEntities.Letters.First(l => l.Id == letter.Id);
        _letterDbEntities.Letters.Remove(letterToBeDeleted);
        _letterDbEntities.SaveChanges();
    }
}

当我添加新信件或删除现有信件时,会在数据库级别添加或删除它们,但它不会反映在列表框中的UI中。我缺少什么?

1 个答案:

答案 0 :(得分:0)

您需要更改var playerA_pts = [ {time: 23.330, x: 70, y:120}, {time: 23.790, x: 75, y: 121}, {time: 23.800, x: 76, y: 123}, ... ] 集合。试试这个:

_letters