2

我有一个 wpf 应用程序,当我使用 Observablecollect 通过 UI 添加新值时,我想更新我的列表视图。但我没有得到我所期望的。当我添加新值时,我不会更新我的列表视图。

这是我的 CS 文件。

 using System.Collections.ObjectModel;
 using System.ComponentModel;
 using System.Data.SqlClient;
 using System.Windows;

 namespace ObservableCollectionTest
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public ObservableCollection<TestUser> NameList { get; set; }

    public MainWindow()
    {
        InitializeComponent();
        NameList = GetNamesFromDBAsStringList();
        ListViewNames.ItemsSource = NameList;
        this.DataContext = this;
    }

    private void Button_Click_1(object sender, RoutedEventArgs e)
    {
        TestUser user = new TestUser();
        user.UserName = txtName.Text;
        NameList.Add(user);

        //InsertUserName(txtName.Text);
        //NameList = GetNamesFromDBAsStringList();

        txtName.Clear();
        MessageBox.Show("User added");
    }

    private ObservableCollection<TestUser> GetNamesFromDBAsStringList()
    {
        ObservableCollection<TestUser> userList = new ObservableCollection<TestUser>();

        SqlConnection connection = new SqlConnection("Data Source=Chakrapani\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True");
        connection.Open();
        string sql = "select UserID,UserName from TestUser";
        SqlCommand command = new SqlCommand(sql, connection);
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            TestUser testUser = new TestUser();
            testUser.UserID = (int)reader[0];
            testUser.UserName = reader[1].ToString();
            userList.Add(testUser);
        }
        reader.Close();
        connection.Close();

        return userList;
    }

    private void InsertUserName(string userName)
    {
        SqlConnection connection = new SqlConnection("Data Source=CHAKRAPANI\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True");
        connection.Open();
        string sql = string.Format("insert into TestUser values ('{0}')", userName);
        SqlCommand command = new SqlCommand(sql, connection);
        command.ExecuteNonQuery();

        connection.Close();
    }
}

public class TestUser : INotifyPropertyChanged
{
    private int _userId;
    private string _userName;

    public int UserID
    {
        get { return _userId; }
        set
        {
            _userId = value;
            NotifyPropertyChanged("UserID");
        }
    }
    public string UserName
    {
        get { return _userName; }
        set
        {
            _userName = value;
            NotifyPropertyChanged("UserName");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
}

这是我的 xaml 文件

<Window x:Class="ObservableCollectionTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="396">
<Grid>
    <Button Content="Add User" HorizontalAlignment="Left" Margin="300,10,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click_1" Name="BtnAdd"/>
    <TextBox HorizontalAlignment="Left" Height="23" Margin="10,10,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="264" Name="txtName"/>
    <ListView HorizontalAlignment="Left" Height="259" Margin="10,51,0,0" VerticalAlignment="Top" Width="264" Name="ListViewNames" ItemsSource="{Binding MyUserNameList}">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="User ID" DisplayMemberBinding="{Binding UserID}"/>
                <GridViewColumn Header="User Name" DisplayMemberBinding="{Binding UserName}"/>
            </GridView>
        </ListView.View>
    </ListView>

</Grid>

请给我一个线索来处理这个问题。

4

2 回答 2

1

您应该将其插入可观察集合而不是重新构建它

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    TestUser user = new TestUser();
    user.UserName = txtName.Text;
    InsertUserName(txtName.Text);
    NameList.Add(new TestUser {UserName = txtName.Text, UserID = ???}); //TODO: assign correct ID
    txtName.Clear();
    MessageBox.Show("User added");
}
于 2013-03-04T10:17:55.087 回答
1

您忘记在构造函数中添加 DataContext :

this.DataContext = this;
于 2013-03-04T10:15:16.603 回答