我有一个datagrid
,在没有hashfunction
的情况下完全正常。
问题场景如下:
我创建了一个按钮,给它一个命令(XAML)并在该按钮的RelayCommand
中创建了ViewModel
。
现在RelayCommand
有一个CanExecute
方法,我在其中创建了绑定到DataTable
的{{1}}哈希值。
我这样做,因此我可以跟踪对DataGrid
进行的更改。
但每次如果我在DataTable
中插入或删除某些内容(绑定到DataTable
),DataGrid
中行的焦点就会丢失。
我不明白为什么会这样。
我的DataGrid
代码:
RelayCommand
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Input;
namespace AM.ViewModel
{
public class RelayCommand : ICommand
{
#region Fields
private readonly Action<object> _execute;
private readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
// Action<object> -> Verkapselung einer parameterlosen Methode
public RelayCommand(Action<object> execute) : this(execute, null) { }
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
{
throw new ArgumentNullException("execute");
}
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter) { _execute(parameter); }
#endregion // ICommand Members
}
}
代码:
Hashfunction
private string CreateHash(DataTable dt)
{
DataContractSerializer serializer = new DataContractSerializer(typeof(DataTable));
var memoryStream = new MemoryStream();
serializer.WriteObject(memoryStream, dt);
byte[] serializedData = memoryStream.ToArray();
// Calculte the serialized data's hash value
var SHA = new SHA1CryptoServiceProvider();
byte[] hash = SHA.ComputeHash(serializedData);
// Convert the hash to a base 64 string
return Convert.ToBase64String(hash);
}
方法:
CanExecute
按钮的XAML:
private bool SaveExecuteCommand(object obj)
{
try
{
if (_InternalCheckActive)
{
hashCurrent = CreateHash(Adresses);
if (!hashCurrent.Equals(hashSaved))
{
return true;
}
else
{
return false;
}
}
else if (_DBCheckActive)
{
hashCurrent = CreateHash(AdressesDBRelevant);
if (!hashCurrent.Equals(hashSaved))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
Logging.Errorlogger.CheckDirectoyAndWriteToLog(ex);
System.Windows.MessageBox.Show(ex.Message, "Fehler - AdressManager", MessageBoxButton.OK, MessageBoxImage.Error);
return false;
}
}