首先,请确保项目同时引用了 Microsoft.Expression.Interactions 和 System.Windows.Interactivity DLL。
自定义Behavior文件:
MyBehavior.cs
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Interactivity; namespace behaviorTest { public class MyBehavior:Behavior<TextBlock> { public MyBehavior() { } protected override void OnAttached() { base.OnAttached(); AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown); } void AssociatedObject_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MessageBox.Show(AssociatedObject.Text.ToString()); } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.MouseLeftButtonDown-=new MouseButtonEventHandler(AssociatedObject_MouseLeftButtonDown); } } }
前台页面:
<UserControl x:Class="behaviorTest.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas./markup-compatibility/2006" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:my="clr-namespace:behaviorTest" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="400"> <Grid x:Name="LayoutRoot" Background="White"> <TextBlock x:Name="tb" Text="HelloWorld" HorizontalAlignment="Center" VerticalAlignment="Center"> <!--<i:Interaction.Behaviors> <my:MyBehavior /> </i:Interaction.Behaviors>--> </TextBlock> </Grid> </UserControl>
如果在后台加入Behavior的话,请看代码:
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; using System.Windows.Interactivity; using Microsoft.Expression.Interactivity.Layout; namespace behaviorTest { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); //自带的拖动行为 //Interaction.GetBehaviors(tb).Add(new MouseDragElementBehavior()); //自己定义的行为 Interaction.GetBehaviors(tb).Add(new MyBehavior()); } } }
本文来自sb001的博客,原文地址:http://www.cnblogs.com/caok168/archive/2012/09/22/2698062.html