这里说下为什么用反射:因为我传递进来的对象是不同的,编辑界面也是使用了propertytools.wpf 这个工具进行的自动生成,所以我并不知道传递进来的对象会是哪个对象。所以用了反射保存原数据最后再用反射进行属性回退。以上功能都实现很好,但是在取消结束编辑界面返回到主界面也就是DataGrid控件后发现通过反射更改的属性值在DataGrid内没有改回来,
举个例子:传递编辑界面了一个 class student{name = 张三},在编辑界面改为 name = 李四,最后点击取消使用反射又将name=张三,此时name 虽然实际值是“张三”,但是在DataGrid显示的却是“李四”。
我在取消返回时也使用了一些方法尝试刷新DataGrid但是都没有用:
RaisePropertyChanged(nameof(TcpSettings));
obj.TcpDg.GetBindingExpression(ItemsControl.ItemsSourceProperty)?.UpdateSource();
以上两种方法我都试过无法刷新



我的反射代码
//存储
foreach (var propertyInfo in comBase.GetType().GetProperties())
{
try
{
object obj = propertyInfo.GetValue(comBase, null);
if(!obj.GetType().IsArray)
copyProperty.Add(propertyInfo.Name,obj);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
//比较赋值
foreach (var propertyInfo in comBase.GetType().GetProperties())
{
try
{
object value = propertyInfo.GetValue(comBase, null);
if (copyProperty.ContainsKey(propertyInfo.Name))
{
var x = copyProperty[propertyInfo.Name];
if(!x.Equals(value))
propertyInfo.SetValue(comBase,x,null);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
}
前台绑定代码
<GroupBox Header="Tcp通讯" Visibility="{Binding TcpSettings.Count,Converter={StaticResource CountToVisConvertor}}">
<DataGrid x:Name="TcpDg" GotFocus="TcpDg_OnGotFocus" ItemsSource="{Binding TcpSettings}" SelectedItem="{Binding SelectedItem}">
<DataGrid.Columns>
<DataGridTextColumn Header="名称" Binding="{Binding Name}"/>
<DataGridTextColumn Header="描述" Binding="{Binding Description}"/>
<DataGridTextColumn Header="解析模块名称" Binding="{Binding AnalyserName}"/>
<DataGridTextColumn Header="Ip地址" Binding="{Binding IP}"/>
<DataGridTextColumn Header="端口" Binding="{Binding Port}"/>
</DataGrid.Columns>
</DataGrid>
</GroupBox>