用toolkit.mvvm框架更新datagrid,在[RelayCommand]中绑定的代码中可以更新datagrid,同样的代码放到代码块中调用就无法更新datagrid。
(使用vs2022community编程)
使用这段代码可以更新
[RelayCommand]
private void AddNew()
{
Employees.Add(new Employee { CardId = "138", OrganizationName = "Raj" });//可以对datagrid进行更新
//LoadExcelToList2();//这个不能更新datagrid不知道为什么,代码一样啊
}
使用这段代码无法更新,不知道为什么
[RelayCommand]
private void AddNew()
{
LoadExcelToList2();//这个不能更新datagrid不知道为什么,代码一样啊
}
public static void LoadExcelToList2()
{
var MyVM = new ViewModel();
MyVM.Employees.Add(new Employee { CardId = "168", OrganizationName = "Raj"});
}
完整代码如下:
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.ComponentModel;
using System.Windows;
namespace WpfToolkitTest
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
//DataContext = new ViewModel();
}
}
public partial class ViewModel : ObservableObject
{
public BindingList<Employee> Employees { get; set; }
public ViewModel()
{
Employees = new BindingList<Employee>();
}
[RelayCommand]
private void AddNew()
{
Employees.Add(new Employee { CardId = "138", OrganizationName = "Raj" });//可以对datagrid进行更新
//LoadExcelToList2();//这个不能更新datagrid不知道为什么,代码一样啊
}
public static void LoadExcelToList2()
{
var MyVM = new ViewModel();
MyVM.Employees.Add(new Employee { CardId = "168", OrganizationName = "Raj"});
}
}
}
using CommunityToolkit.Mvvm.ComponentModel;
namespace WpfToolkitTest
{
public partial class Employee : ObservableObject
{
public string OrganizationName { get; set; }
[ObservableProperty]
private string cardId;//读卡器读取的卡号
}
}
<Window x:Class="WpfToolkitTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfToolkitTest"
xmlns:hc="https://handyorg.github.io/handycontrol"
Title="{Binding Title}"
Width="900"
Height="600"
WindowStartupLocation="CenterScreen"
mc:Ignorable="d" >
<Window.DataContext>
<local:ViewModel/>
</Window.DataContext>
<DockPanel Margin="5">
<hc:UniformSpacingPanel Margin="0,5,0,0"
Spacing="10"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<Button Content="Add New" Command="{Binding AddNewCommand}"/>
</hc:UniformSpacingPanel>
<DataGrid Name="dataGrid"
d:ItemsSource="{d:SampleData ItemCount=10}"
ItemsSource="{Binding Employees}"
CanUserAddRows="False"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="卡号" Binding="{Binding CardId}"/>
<DataGridTextColumn Header="机构名称" Binding="{Binding OrganizationName}"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>