自定义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();
}