一般行为 [英] Generic Behavior

查看:73
本文介绍了一般行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一般行为.我的问题是XAML中的通用声明.

I would like create generic behavior. My problem is generic declaration in XAML.

    public class GenericBehavior<T> : Behavior<DataGrid>
        where T : class 
    {
    }

我不能使用 x:TypeArguments ,因为我没有宽松的XAML文件.

I can’t use x:TypeArguments because I don’t have loose XAML file.

在WPF中,当定位.NET Framework 4时,可以使用XAML 2009功能与x:TypeArguments一起使用,但仅适用于宽松的XAML(XAML那不是标记编译的).标记编译的XAML for WPF和XAML的BAML形式当前不支持XAML 2009关键字,并且功能

In WPF and when targeting .NET Framework 4, you can use XAML 2009 features together with x:TypeArguments but only for loose XAML (XAML that is not markup-compiled). Markup-compiled XAML for WPF and the BAML form of XAML do not currently support the XAML 2009 keywords and features

我发现了一些解决方法与MarkupExtension但行为无法正常工作.

I found some workaround with MarkupExtension but with Behaviors not work.

在当前解决方案中我将行为附加在代码中.

有什么主意吗?

推荐答案

您可以在视图模型内创建通用行为,然后使用附加属性将其注入到控件中.

you can create the generic Behavior inside your view model then inject it to your control using attached properties.

public class ViewModel
{
    public Behavior MyBehavior
    { 
        get 
        {
            return new GenericBehavior<SomeType>();
        } 
    }
}

public class AttachedBehaviors
{
    public static Behavior GetBehavior(DependencyObject sender) => (Behavior)sender.GetValue(BehaviorProperty);
    public static void SetBehavior(DependencyObject sender, Behavior value) => sender.SetValue(BehaviorProperty, value);

    public static readonly DependencyProperty BehaviorProperty =
        DependencyProperty.RegisterAttached("Behavior", typeof(Behavior), typeof(AttachedBehaviors),
            new PropertyMetadata(null, new PropertyChangedCallback(BehaviorChanged)));

    private static void BehaviorChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        if (sender is FrameworkElement elem)
        {
            if (e.NewValue is Behavior behavior)
            {
                BehaviorCollection Behaviors = Interaction.GetBehaviors(elem);
                Behaviors.Add(behavior);
            }
        }
    }

}

public class GenericBehavior<T> : Behavior<DataGrid> where T : class
{
    public T TestValue { get; set; }

    protected override void OnAttached()
    {
    }
}

现在您可以像这样使用它

now you can use it like this

<DataGrid local:AttachedBehaviors.Behavior="{Binding MyBehavior}" > 
</DataGrid>

PS:您只需要安装 Microsoft.Xaml.Behaviors.Wpf NuGet软件包.

PS: you just need to install Microsoft.Xaml.Behaviors.Wpf NuGet package.

这篇关于一般行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆