C#WPF MVVM当我从DataGrid值

时间:2018-03-05 12:17:07

标签: c# wpf mvvm datagrid

我有一个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;
    }
}

0 个答案:

没有答案