這可以用ICommand
實現,需要一個Map
實例,因爲它是命令的參數來實現:
//WARNING: all code typed in SO window
public class DeleteMapsCommand : ICommand
{
private Database _db;
public DeleteMapsCommand(Database db)
{
_db = db;
}
public void CanExecute(object parameter)
{
//only allow delete if the parameter passed in is a valid Map
return (parameter is Map);
}
public void Execute(object parameter)
{
var map = parameter as Map;
if (map == null) return;
_db.Delete(map);
_db.Commit();
}
public event EventHandler CanExecuteChanged; //ignore this for now
}
然後你創建你的視圖模型的公共屬性,露出命令
public class ViewModel
{
public ViewModel() {
//get the Database reference from somewhere?
this.DeleteMapCommand = new DeleteMapsCommand(this.Database);
}
public ICommand DeleteMapCommand { get; private set; }
}
的實例
最後,您需要將您的操作綁定到命令屬性和將命令屬性綁定到要刪除的映射。你真的沒有給我足夠的XAML中的陳述應如何在你的情況來完成,但你可以做類似下面的一個ListBox
:
<ListBox x:Name="ListOfMaps" ItemsSource="{Binding AllTheMaps}" />
<Button Command="{Binding DeleteMapCommand}" CommandParameter="{Binding SelectedItem, ElementName=ListOfMaps}">Delete Selected Map</Button>
更新
要附加該命令的事件,您可以使用附加屬性:
public static class Helper
{
public static IComparable GetDeleteMapCommand(DependencyObject obj)
{
return (IComparable)obj.GetValue(DeleteMapCommandProperty);
}
public static void SetDeleteMapCommand(DependencyObject obj, IComparable value)
{
obj.SetValue(DeleteMapCommandProperty, value);
}
public static readonly DependencyProperty DeleteMapCommandProperty =
DependencyProperty.RegisterAttached("DeleteMapCommand", typeof(IComparable), typeof(Helper), new UIPropertyMetadata(null, OnDeleteMapCommandChanged));
private static void OnDeleteMapCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
//when we attach the command, grab a reference to the control
var mapControl = sender as MapControl;
if (mapControl == null) return;
//and the command
var command = GetDeleteMapCommand(sender);
if (command == null) return;
//then hook up the event handler
mapControl.Deleting += (o,e) =>
{
if (command.CanExecute(e.Maps))
command.Execute(e.Maps);
};
}
}
然後,您需要綁定這樣的命令:
<MapControl local:Helper.DeleteMapCommand="{Binding DeleteMapCommand}" />
現在,您的視圖模型沒有引用視圖特定的類型。
從你展示的代碼中,ViewModel中沒有「視圖邏輯」。您的視圖模型並不知道視圖,它只知道它有一個名爲OnDeleting的方法,它是執行時的命令處理程序。我不確定你在擔心什麼。你有錯誤嗎?命令是否正在發射? – Thelonias
是的everythink偉大的作品,即時通訊如果我的編程風格是正確的。我想學習乾淨的編碼,我的感覺是,將視圖eventargs傳遞給視圖模型並不那麼幹淨。是嗎? – slopsucker