yinyuessh

导航

自定义Behavior

自定义Behavior

实现功能

在鼠标滚轮滚动时,ComboBox的SelectIndex也实现递增和递减

Code

public class ComboxMouseWheelBehavior : Behavior<ComboBox>
{
    protected override void OnAttached()
    {
        AssociatedObject.MouseWheel += ComboxMouseWheel;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.MouseWheel -= ComboxMouseWheel;
    }

    private void ComboxMouseWheel(object sender, MouseWheelEventArgs e)
    {
       if(e.Delta > 0)
        {
            if(AssociatedObject.SelectedIndex >0)
                AssociatedObject.SelectedIndex -= 1;
        }
        else
        {
            if(AssociatedObject.SelectedIndex < AssociatedObject.Items.Count - 1)
                AssociatedObject.SelectedIndex += 1;
        }
    }
}
<ComboBox>
    <i:Interaction.Behaviors>
        <local:ComboxMouseWheelBehavior/>
    </i:Interaction.Behaviors>
</ComboBox>

在将Behavior附加到ComboBox时,AssociatedObject=被附加的DependencyObject,再调用OnAttached方法,在Behavior被分离会调用OnDetaching方法

源码

public void Attach(DependencyObject dependencyObject)
{
    if (dependencyObject != this.AssociatedObject)
    {
        if (this.AssociatedObject != null)
        {
            throw new InvalidOperationException();
        }

        if (Interaction.ShouldRunInDesignMode || !(bool)this.GetValue(DesignerProperties.IsInDesignModeProperty))
        {
            this.WritePreamble();
    -->     this.associatedObject = dependencyObject;
            this.WritePostscript();
        }
    -->   this.OnAttached();
    }
}

public void Detach()
{
 -->   this.OnDetaching();
    this.WritePreamble();
    this.associatedObject = null;
    this.WritePostscript();
}

posted on 2024-05-09 11:02  音乐随生活  阅读(10)  评论(0编辑  收藏  举报