【发布时间】:2014-06-02 15:24:32
【问题描述】:
我正在 WPF 应用程序中实现附加行为。我需要将类型参数传递给行为,因此我可以在SqliteBoundRow 上调用方法void NewRow(Table<T> table)。如果我在 XAML 中实例化一个对象,我会使用 x:TypeArguments 传递一个类型参数,但在设置附加行为时我看不到这样做的方法,因为它使用静态属性。
附加行为的代码如下所示:
public abstract class SqliteBoundRow<T> where T : SqliteBoundRow<T>
{
public abstract void NewRow(Table<T> table);
}
public class DataGridBehavior<T> where T:SqliteBoundRow<T>
{
public static readonly DependencyProperty IsEnabledProperty;
static DataGridBehavior()
{
IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled",
typeof(bool), typeof(DataGridBehavior<T>),
new FrameworkPropertyMetadata(false, OnBehaviorEnabled));
}
public static void SetIsEnabled(DependencyObject obj, bool value)
{
obj.SetValue(IsEnabledProperty, value);
}
public static bool GetIsEnabled(DependencyObject obj)
{
return (bool)obj.GetValue(IsEnabledProperty);
}
private static void OnBehaviorEnabled(DependencyObject dependencyObject,
DependencyPropertyChangedEventArgs args)
{
var dg = dependencyObject as DataGrid;
dg.InitializingNewItem += DataGrid_InitializingNewItem;
}
private static void DataGrid_InitializingNewItem(object sender,
InitializingNewItemEventArgs e)
{
var table = (sender as DataGrid).ItemsSource as Table<T>;
(e.NewItem as T).NewRow(table);
}
}
XAML 如下所示:
<DataGrid DataGridBehavior.IsEnabled="True">
<!-- DataGridBehavior needs a type parameter -->
</DataGrid>
我目前的解决方案是将 DataGridBehavior 包装在指定类型参数的派生类中。
【问题讨论】:
标签: c# wpf attachedbehaviors