我創建了一個類來爲DataGrid
保留一些額外的行爲。我會簡化它的功能,因爲它現在不重要。如何調用DependencyProperty中的按鈕單擊或事件
當用戶按Up
或Down
鍵時,它將執行一個私有的本地方法DataGridHelper
class;完成了。但是,當用戶按Right
或Left
我想發起事件或從外面點擊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,有的風格將無法如此。
你不應該調用'Button'點擊。在WPF中,你應該使用視圖模型的'ICommand's,它將綁定到你的視圖。 – dymanoid
我以爲是。我需要一些幫助來完成我在XAML部分編寫的內容。 – Murilo