尝试将一个视图模型中的 wpf 数据网格中的选定行传递到另一个视图模型进行编辑。我可以选择该行并将其放入属性中。但无法将其传递给不同视图模型中的另一个属性。
这是选择行的视图模型中的代码:
using Checkbook8.Data;
using System.Collections.ObjectModel;
namespace Checkbook8.Views
{
internal class ChkbkTransactionListViewModel : BindableBase
{
private ObservableCollection<ChkbkTransaction>? _ChkbkRecordCol;
public ChkbkTransactionListViewModel()
{
GetData();
}
private void GetData()
{
using (var context = new ChkbkTransactionDbContext())
{
_ChkbkRecordCol = new ObservableCollection<ChkbkTransaction> (context.ChkbkTransactions.ToList());
}
}
public ObservableCollection<ChkbkTransaction>? ChkbkRecordCol
{
get => _ChkbkRecordCol;
set => SetProperty(ref _ChkbkRecordCol, value);
}
private static ChkbkTransaction? _SelectedTransaction;
public ChkbkTransaction? SelectedTransaction
{
get => _SelectedTransaction;
set => SetProperty(ref _SelectedTransaction, value);
}
private static ChkbkTransactionListViewModel _Instance = new();
public static ChkbkTransactionListViewModel Instance { get { return _Instance; } }
}
}
这是我尝试将 SelectedTransaction 属性传递给的代码:
using Checkbook8.Data;
namespace Checkbook8.Views
{
internal class EditTransactionViewModel : BindableBase
{
private ChkbkTransaction _TransactionSelected;
public ChkbkTransaction TransactionSelected
{
get => _TransactionSelected;
set
{
value = ChkbkTransactionListViewModel.Instance.SelectedTransaction;
SetProperty(ref _TransactionSelected, value);
}
}
}
}
我做错了什么?
EditTransactionViewModel.TransactionSelected
的设置者有点不寻常。它似乎从未被调用过,并且忽略了传入的值,这确实很奇怪。因此,您可能只需删除 setter 并保留可编辑的 TransactionSelected
属性
与ChkbkTransactionListViewModel
中的同步。internal class EditTransactionViewModel : BindableBase
{
public EditTransactionViewModel()
{
ChkbkTransactionListViewModel.Instance.PropertyChanged += (o, e) =>
{
if (e.PropertyName == nameof(ChkbkTransactionListViewModel.TransactionSelected)
{
SetProperty(ref _TransactionSelected,
ChkbkTransactionListViewModel.Instance.TransactionSelected);
}
}
}
private ChkbkTransaction _TransactionSelected;
public ChkbkTransaction TransactionSelected => _TransactionSelected;
}