c# - 添加新的客户MVVM WPF后刷新Datagrid

标签 c# wpf mvvm datagrid

这是我的看法

enter image description here

XAML查看主:

<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 添加角色:
enter image description here

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/

相关文章:

c# - 为什么我的 WCF 客户端在调用引发事件的 WCF 服务器中的方法后超时?

wpf - 基于 DateTime 创建自定义 GroupDescription

wpf - 将性别表正常化是否太过分了?

c# - 通过 WPF 中的 ViewModel 将值绑定(bind)到组合框

c# - 在 .NET winform 中重现表格模型

c# - 无法在 nvarchar 上调用方法

c# - ObservableCollection 和 INotifyPropertyChanged 的​​ WPF MVVM 问题

由于绑定(bind)错误,WPF DataGrid 分组不显示

c# - 使用大数据填充 DataGridView 时性能低下

wpf - 将 WPF 按钮图像“灰显”?