2016-11-11 67 views
2

我創建了一個類來爲DataGrid保留一些額外的行爲。我會簡化它的功能,因爲它現在不重要。如何調用DependencyProperty中的按鈕單擊或事件

當用戶按UpDown鍵時,它將執行一個私有的本地方法DataGridHelper class;完成了。但是,當用戶按RightLeft我想發起事件或從外面點擊Button。當用戶按左或右時,它將改變當前頁面(重做搜索)。我想在許多DataGrid中重複使用這個PreviewKeyDown

我有一些想法,但我很困惑。我會創建另一個DependencyProperty來傳遞Button id,所以我必須在Visual Tree中進行搜索,但我不知道這是否是最好的方法。我想這樣做:

<DataGrid x:name="myGrid" 
      Help:DataGridHelper.CustomGrid="True" 
      Help:DataGridHelper.OnLeftRight="myGrid_OnLeftRight" /> 

private void myGrid_OnLeftRight(object sender, CustomEventArgs e) 
{ 
    if(e.Key == "Left")..... 
} 

這是我到目前爲止已經完成:

public class DataGridHelper 
{ 
    public static readonly DependencyProperty CustomGridProperty = DependencyProperty.RegisterAttached("CustomGrid", typeof(bool), typeof(DataGridHelper), new FrameworkPropertyMetadata(false, CustomGridCallback)); 

     [AttachedPropertyBrowsableForType(typeof(DataGrid))] 
     public static bool GetCustomGrid(DependencyObject obj) 
     { 
      return (bool)obj.GetValue(CustomGridProperty); 
     } 


     [AttachedPropertyBrowsableForType(typeof(DataGrid))] 
     public static void SetCustomGrid(DependencyObject obj, bool value) 
     { 
      obj.SetValue(CustomGridProperty, value); 
     } 

     private static void CustomGridCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) 
     { 
      var dataGrid = (DataGrid)d; 

      if ((bool)e.NewValue == false) 
      { 
       dataGrid.PreviewKeyDown -= DataGrid_PreviewKeyDown; 
      } 
      else 
      { 
       dataGrid.PreviewKeyDown += DataGrid_PreviewKeyDown; 
      } 
     }  

     private static void DataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) 
     { 
      if (e.Key == Key.Down || e.Key == Key.Up) 
       DoMyStuff(); // static method in DataGridHelper class 

      if(e.Key == Key.Left || e.Key == Key.Right) 
      // here I want to invoke a button click 
      // or here I want to invoke a passed method from view 
     } 
} 

我不想創造這樣MyDataGrid : DataGrid一類,因爲我用MahApps,有的風格將無法如此。

+3

你不應該調用'Button'點擊。在WPF中,你應該使用視圖模型的'ICommand's,它將綁定到你的視圖。 – dymanoid

+0

我以爲是。我需要一些幫助來完成我在XAML部分編寫的內容。 – Murilo

回答

1

這種方法是錯誤的。

在WPF中記住一個簡單的通用規則:如果您在代碼隱藏中使用事件來調用業務邏輯,那麼您就錯了。

您應該使用的輸入綁定或附加行爲/混合SDK互動行爲通過在ViewModel結合的事件或特定的按鈕手勢Commands得到你想要的行爲。

在XAML中某處(DataGridTemplateColumn.CellTemplate爲例):

<i:Interaction.Triggers> 
     <i:EventTrigger EventName="LeftButtonUp"> 
      <i:InvokeCommandAction Command={Binding LeftButtonActionCommand}/> 
     </i:EventTrigger> 
<i:Interaction.Triggers> 
+0

謝謝,但我現在還不知道什麼。我會查看一些關於你所說的內容的信息。 – Murilo

+0

我有代碼隱藏,但它只調用ViewModel方法,但我不使用ICommand – Murilo

+0

然後,您沒有正確使用'MVVM',因爲你有'View'和'ViewModel'之間的硬依賴關係。正如我所說 - 這是一個跡象,你做錯了。看看http://www.wpftutorial.net/給你一些指導。 – toadflakz