我有 2 个页面(用户和用户列表)当我在用户页面上添加新用户然后将页面更改为用户列表页面时,用户列表页面上的ComboBoxUser不会自动更新。有什么想法可以解决这个问题吗?
这是我的代码 User.cs
public class User : INotifyPropertyChanged
{
string _firstName;
public string FirstName {
get { return _firstName; }
set {
_firstName = value;
OnPropertyChanged("FirstName");
OnPropertyChanged("FullName");
}
}
string _lastName;
public string LastName {
get { return _lastName; }
set {
_lastName = value;
OnPropertyChanged("LastName");
OnPropertyChanged("FullName");
}
}
public string FullName
{
get { return string.Format("{0} {1}", FirstName, LastName); }
}
int _gender;
public int Gender {
get { return _gender; }
set {
_gender = value;
OnPropertyChanged("Gender");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
UserListingViewModel.cs
public class UserListingViewModel : INotifyPropertyChanged
{
public UserListingViewModel()
{
LoadDataUser();
}
public void LoadDataUser()
{
ComboUserData = new ObservableCollection<User>();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings[
"dLondre.Properties.Settings.CSLONDRE"].ConnectionString);
string str = "";
str += "SELECT userid,firstname + ' ' + lastname as name FROM [user] ";
SqlCommand com = con.CreateCommand();
com.CommandText = str;
try
{
con.Open();
SqlDataReader sdr = com.ExecuteReader();
while (sdr.Read())
{
ComboUserData.Add(new User { UserID = (string)sdr["userid"], FirstName = (string)sdr["name"]});
}
com.Dispose();
con.Close();
con.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
ObservableCollection<User> _comboUserData;
public ObservableCollection<User> ComboUserData
{
get
{
if (_comboUserData == null)
_comboUserData = new ObservableCollection<User>();
return _comboUserData;
}
set
{
if (value != _comboUserData)
_comboUserData = value;
OnPropertyChanged("ComboUserData");
}
}
User _user;
public User SelectedUserID
{
get { return _user; }
set
{
_user = value;
OnPropertyChanged("SelectedUserID");
}
}
}
这是我的 XAML
<ComboBox x:Name="DDUserId"
Width="140"
DisplayMemberPath="FirstName"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding ComboUserData, Mode=TwoWay}"
SelectedItem="{Binding SelectedUserID}">
</ComboBox>
主窗口 XAML
<mui:LinkGroup DisplayName="welcome">
<mui:LinkGroup.Links>
<mui:Link DisplayName="Login" Source="/Views/Login.xaml" />
<mui:Link DisplayName="Register User" Source="/Views/UserView.xaml" />
<mui:Link DisplayName="Manage Group" Source="/Views/UserGroupView.xaml" />
<mui:Link DisplayName="List User" Source="/Views/UserListingView.xaml" />
</mui:LinkGroup.Links>
</mui:LinkGroup>