我有一个主从应用程序,其中详细 View 模型/ View 能够执行删除命令。
但是我怎样才能通知主视图模型中的主集合细节 View 模型被删除并且必须从集合中删除?
这是一个糟糕的设计,主视图模型必须删除细节吗?
或者是通过事件做到这一点的唯一选择? MVVM 符合?
这是一个缩短的代码
查看型号
public class AllMetalTransactionViewModel : WorkspaceViewModel
{
private ObservableCollection<MetalTransactionViewModel> _metalTransactions;
public ObservableCollection<MetalTransactionViewModel> MetalTransactions
{
get { return _metalTransactions; }
set
{
if (Set("MetalTransactions", ref _metalTransactions, value))
{
}
}
}
private MetalTransactionViewModel _selectedMetalTransaction;
public MetalTransactionViewModel SelectedMetalTransaction
{
get { return _selectedMetalTransaction; }
set
{
if (Set("SelectedMetalTransaction", ref _selectedMetalTransaction, value))
{
}
}
}
}
public class MetalTransactionViewModel : WorkspaceViewModel
{
private RelayCommand _deleteCommand;
public RelayCommand DeleteCommand
{
get
{
return _deleteCommand
?? (_deleteCommand = new RelayCommand(
() =>
{
if (!IsNewUnit)
{
_dataService.DeleteMetalTransaction(_metalTransaction, CallbackDelete);
_dataService.CommitAllChanges(delegate(bool b, object o) { });
// How can I inform the AllMetalTransactionViewModel that I'm deleted? Event?
}
},
() => !IsNewUnit));
}
}
}
XAML-Master
<View:MetalTransactionView Grid.Column="1"
DataContext="{Binding SelectedMetalTransaction}"></View:MetalTransactionView>
XAML 详细信息
<Button DockPanel.Dock="Right" HorizontalAlignment="Right"
Padding="5" Content="Löschen" Margin="5" Width="80"
Command="{Binding Path=DeleteCommand}" />
最佳答案
祝你有美好的一天!
您可以通过多种方式进行操作(我喜欢 A 和 D 解决方案):
答:细节 View 模型有一个链接到主细节 View 模型(一些带有一种方法的轻接口(interface)void RemoveDetail(MetalTransactionViewModel detail)
)或细节 View 模型集合。
例如(那里有收藏链接):
详细 View 模型:
public class MetalTransactionViewModel : WorkspaceViewModel
{
private RelayCommand _deleteCommand;
IList<MetalTransactionViewModel> ParentCollection { get; }
public RelayCommand DeleteCommand
{
get
{
return _deleteCommand
?? (_deleteCommand = new RelayCommand(
() =>
{
if (!IsNewUnit)
{
_dataService.DeleteMetalTransaction(_metalTransaction, CallbackDelete);
_dataService.CommitAllChanges(delegate(bool b, object o) { });
if (ParentCollection == null) { return; }
if (ParentCollection.Contains(this)) { ParentCollection.Remove(this); }
}
},
() => !IsNewUnit));
}
}
}
在主视图模型中,创建详细 View 模型时:
private MetalTransactionViewModel CreateDetailViewModel()
{
return new MetalTransactionViewModel() { ParentCollection = MetalTransactions };
}
B. 使用您所说的事件(但 小心 ,因为 它可能会给您带来内存泄漏 )。请查看 WeakEventManager
C.如果您使用的是 mvvm 工具包,例如 MVVM Light Toolkit您可以使用 Messenger类通知主视图模型删除操作。
D. 将删除命令移至主视图模型。我想在这种情况下这是最好的解决方案。我相信主视图模型必须操纵集合细节 View 模型 .
我希望它会帮助你!
关于c# - 详细 View 中的自删除 View 模型 - 不好的做法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647216/