将类型参数传递给附加行为

tdr*_*tdr 4 c# wpf attachedbehaviors

我正在WPF应用程序中实现附加行为.我需要传递一个类型参数的行为,这样我就可以调用一个方法void NewRow(Table<T> table)SqliteBoundRow.如果我在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);
    }

}
Run Code Online (Sandbox Code Playgroud)

XAML看起来像这样:

<DataGrid DataGridBehavior.IsEnabled="True">
    <!-- DataGridBehavior needs a type parameter -->
</DataGrid>
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是将DataGridBehavior包装在一个指定类型参数的派生类中.

She*_*dan 6

最简单的解决方案是您声明另一个Attached Property,但类型Type为您保存参数值.在这种情况下,您可以在以下情况Type之前设置属性IsEnabled Attached Property:

<DataGrid DataGridBehavior.TypeParameter="{x:Type SomePrefix:SomeType}" 
    DataGridBehavior.IsEnabled="True" ... />
Run Code Online (Sandbox Code Playgroud)

再看看你的代码,好像你的IsEnabled属性除了在你的表中添加一个新行之外什么都不做......在这种情况下,你没有理由不能用它替换它TypeParameter Attached Property并使用那个来添加新行代替.