2009-09-01 98 views
2

如何將WPF控件上的事件綁定到ViewModel上的方法?將ViewModel上的方法附加到WPF中的事件

我有一個視圖模型:

class MyViewModel { 
    public string MyText { get; set; } 
    public void MyMouseHandleMethod(object sender, EventArgs e) { } 
} 

在一個DataTemplate我有:

<TextBlock Text="{Binding Text}"> 

現在,我想在我的視圖模型附加一個方法TextBlock的,是這樣的:

<TextBlock Text="{Binding MyText}" MouseUp="{Binding MyMouseHandleMethod}"> 

我不知道如何做到這一點,而無需在代碼隱藏中創建回調。

回答

3

查看here的使用AttachedCommandBehavior。它允許您將命令完全綁定到XMAL中的事件。不完全是你想要的,但它會給你相同的結果。

+0

不是我最喜歡的解決方案,但它的工作原理。 – Hallgrim 2009-09-03 19:16:26

1

我有一個新的解決方案,在.NET 4.5+中使用事件的自定義標記擴展。它可與多個參數,綁定等擴展功能可用於提供參數值,等我完全這裏詳細解釋一下:

http://www.singulink.com/CodeIndex/post/building-the-ultimate-wpf-event-method-binding-extension

用法:

<!-- Basic usage --> 
<Button Click="{data:MethodBinding OpenFromFile}" Content="Open" /> 

<!-- Pass in a binding as a method argument --> 
<Button Click="{data:MethodBinding Save, {Binding CurrentItem}}" Content="Save" /> 

<!-- Another example of a binding, but this time to a property on another element --> 
<ComboBox x:Name="ExistingItems" ItemsSource="{Binding ExistingItems}" /> 
<Button Click="{data:MethodBinding Edit, {Binding SelectedItem, ElementName=ExistingItems}}" /> 

<!-- Pass in a hard-coded method argument, XAML string automatically converted to the proper type --> 
<ToggleButton Checked="{data:MethodBinding SetWebServiceState, True}" 
       Content="Web Service" 
       Unchecked="{data:MethodBinding SetWebServiceState, False}" /> 

<!-- Pass in sender, and match method signature automatically --> 
<Canvas PreviewMouseDown="{data:MethodBinding SetCurrentElement, {data:EventSender}, ThrowOnMethodMissing=False}"> 
    <controls:DesignerElementTypeA /> 
    <controls:DesignerElementTypeB /> 
    <controls:DesignerElementTypeC /> 
</Canvas> 

    <!-- Pass in EventArgs --> 
<Canvas MouseDown="{data:MethodBinding StartDrawing, {data:EventArgs}}" 
     MouseMove="{data:MethodBinding AddDrawingPoint, {data:EventArgs}}" 
     MouseUp="{data:MethodBinding EndDrawing, {data:EventArgs}}" /> 

<!-- Support binding to methods further in a property path --> 
<Button Content="SaveDocument" Click="{data:MethodBinding CurrentDocument.DocumentService.Save, {Binding CurrentDocument}}" /> 

視圖模型方法簽名:

public void OpenFromFile(); 
public void Save(DocumentModel model); 
public void Edit(DocumentModel model); 

public void SetWebServiceState(bool state); 

public void SetCurrentElement(DesignerElementTypeA element); 
public void SetCurrentElement(DesignerElementTypeB element); 
public void SetCurrentElement(DesignerElementTypeC element); 

public void StartDrawing(MouseEventArgs e); 
public void AddDrawingPoint(MouseEventArgs e); 
public void EndDrawing(MouseEventArgs e); 

public class Document 
{ 
    // Fetches the document service for handling this document 
    public DocumentService DocumentService { get; } 
} 

public class DocumentService 
{ 
    public void Save(Document document); 
} 
相關問題