我正在创建一个自定义混合行为来作用于 ListboxItem,即
public class DragtestBehaviour : Behavior<ListBoxItem>
{
public DragtestBehaviour()
{ // Insert code required on object creation below this point.
}
protected override void OnAttached()
{
base.OnAttached();
// Insert code that you would want run when the Behavior is attached to an object.
}
protected override void OnDetaching()
{
base.OnDetaching();
// Insert code that you would want run when the Behavior is removed from an object.
}
}
我无法弄清楚的是如何将它附加到列表框项?
或者,我是否必须为 Listbox 项目设置样式并将其附加到 Border 或任何其他样式元素?如果这是真的,那么我是否还必须从 Border(即框架元素)派生我的行为类?
DragtestBehaviour : Behavior<Frameworkelement>
最佳答案
我基本上已经完成了 Eran otzap 在他的评论中所建议的以及 this article 中所描述的内容。通过马克史密斯。这允许仍然使用混合行为及其好处(如 AssociatedObject
),但在附加它时更加灵活。它是正常附加行为与混合行为的融合。
为了完整起见,这里还有相关的代码。
在 ItemContainerStyle
中附加行为:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource {x:Type ListBoxItem}}">
<Setter Property="behaviors:DragDropBehavior.IsAttached" Value="True" />
</Style>
</ListBox.ItemContainerStyle>
行为
public class DragDropBehavior : Behavior<ListBoxItem>
{
// IsAttached
public static DependencyProperty IsAttachedProperty = DependencyProperty.RegisterAttached("IsAttached",typeof(bool), typeof(DragDropBehavior),new FrameworkPropertyMetadata(false, OnIsAttachedChanged));
public static bool GetIsAttached(DependencyObject o){return (bool)o.GetValue(IsAttachedProperty);}
public static void SetIsAttached(DependencyObject o, bool value){o.SetValue(IsAttachedProperty, value);}
// is called the same as when attached in Interaction.Behaviors tag
protected override void OnAttached()
{
base.OnAttached();
}
// manual attachement to listbox item
private static void OnIsAttachedChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var el = o as UIElement;
if (el != null)
{
var behColl = Interaction.GetBehaviors(el);
var existingBehavior = behColl.FirstOrDefault(b => b.GetType() == typeof(DragDropBehavior)) as DragDropBehavior;
if ((bool)e.NewValue == false && existingBehavior != null)
{
behColl.Remove(existingBehavior);
}
else if ((bool)e.NewValue == true && existingBehavior == null)
{
behColl.Add(new DragDropBehavior());
}
}
}
}
关于wpf - 在 ListboxItem 上添加自定义混合行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20076852/