<DataGrid AutoGenerateColumns="false"
SelectedItem="{Binding Selectedrole}"
ItemsSource="{Binding RoleList}">
<Button Content="Add Role"
Command="{Binding AddRole}"
Height="35"/>
</DataGrid>
ViewModel主:
public RoleManagementViewModel()
{
roleList = new ObservableCollection<UserRoleClass>(WCFclient.GetAllRoles());
_addRole = new RelayCommand<string>(AddRoleFunction);
}
private void AddRoleFunction(object obj)
{
if (!Application.Current.Windows.OfType<SelectionCompartementView>().Any())
{
AddRoleView winAddRole = new AddRoleView();
winAddRole.DataContext = new AddRoleViewModel();
winAddRole.Show();
winAddRole.Topmost = true;
winAddRole.Focus();
}
}
public ObservableCollection<UserRoleClass> RoleList
{
get { return roleList; }
set
{
roleList = value;
OnPropertyChanged("RoleList");
}
}
View 添加角色:
Xaml角色:
<Button x:Name="button1"
Command="{Binding SaveRole}"
CommandParameter="{Binding ElementName=AddRole}"/>
ViewModel角色:
public AddRoleViewModel()
{
_addOrUpdate = new UserRoleClass();
_addOrUpdate = new UserRoleClass();
saveRole = new RelayCommand<Window>(addFunc);
}
private void addFunc(Window window)
{
UserRoleClass newRole = new UserRoleClass()
{
name = AddOrUpdate.name,
description = AddOrUpdate.description,
};
int resultSave = WCFclient.saveRole(newRole);
if (resultSave == 0)
{
String UpdateInformation0 = "Role is saved successfully";
string sCaption = "Save Role";
MessageBoxButton btnMessageBox = MessageBoxButton.OK;
MessageBoxImage icnMessageBox = MessageBoxImage.Information;
MessageBoxResult rsltMessageBox = MessageBox.Show(
UpdateInformation0, sCaption, btnMessageBox, icnMessageBox);
}
if (window != null)
{
window.Close();
}
}
private ICommand saveRole;
public ICommand SaveRole
{
get { return saveRole; }
}
它工作正常:当我添加一个新的
Role
时,Add-Role View 关闭并返回到Main View ,并且我在数据库中有一个结果...但是在MainView中的DataGrid
中却没有。如何直接刷新?
最佳答案
首先,为什么有以下两行?_addOrUpdate = new UserRoleClass();
其次,当您保存新角色时,似乎正在调用将其保存到数据库的WCF服务。
您正在使用一个可观察的集合,当您将其添加到该集合时,该集合应该会更新,但是我看不到您的代码将新角色添加到RoleList
中。
关于c# - 添加新的客户MVVM WPF后刷新Datagrid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44379388/