数据绑定 - WPF 可观察集合与 INotifyPropertyChanged for ListView 不起作用



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

这是我的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>

请给我一个处理这个问题的提示。

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

this.DataContext = this;

你应该把它插入到observable collection中,而不是重新构建它

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");
}

相关内容

  • 没有找到相关文章

最新更新