button 通过Behavior操作textbox内的text

View 代码如下:

View Code
 1 <UserControl x:Class="TestApp.Views.TestView"
2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
5 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
6 xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
7 xmlns:behavior="clr-namespace:TestApp.Behaviors"
8 mc:Ignorable="d"
9 d:DesignWidth="1280" d:DesignHeight="874">
10 <Grid>
11 <StackPanel Orientation="Horizontal" VerticalAlignment="Top">
12 <TextBox x:Name="tbTest"/>
13 <Button Margin="20,0,0,0" Content="delete">
14 <i:Interaction.Behaviors>
15 <behavior:TextOperationBehavior IsDelete="true" AttachedTextBox="{Binding ElementName=tbTest}"/>
16 </i:Interaction.Behaviors>
17 </Button>
18 <Button Margin="20,0,0,0" Content="clear">
19 <i:Interaction.Behaviors>
20 <behavior:TextOperationBehavior IsDelete="false" AttachedTextBox="{Binding ElementName=tbTest}"/>
21 </i:Interaction.Behaviors>
22 </Button>
23 </StackPanel>
24 </Grid>
25 </UserControl>

Code behind 如下:

View Code
 1 using System.Windows;
2 using System.Windows.Controls;
3 using System.Windows.Interactivity;
4
5 namespace TestApp.Behaviors
6 {
7 public class TextOperationBehavior : Behavior<Button>
8 {
9 public static readonly DependencyProperty AttachedTextBoxProperty = DependencyProperty.Register("AttachedTextBox", typeof(TextBox), typeof(TextOperationBehavior));
10 public static readonly DependencyProperty IsDeleteProperty = DependencyProperty.Register("IsDelete", typeof(bool), typeof(TextOperationBehavior));
11
12 public TextBox AttachedTextBox
13 {
14 get { return (TextBox)GetValue(AttachedTextBoxProperty); }
15 set { SetValue(AttachedTextBoxProperty, value); }
16 }
17
18 public bool IsDelete
19 {
20 get { return (bool)GetValue(IsDeleteProperty); }
21 set { SetValue(IsDeleteProperty, value); }
22 }
23
24
25 protected override void OnAttached()
26 {
27 base.OnAttached();
28 if (AssociatedObject != null)
29 {
30 AssociatedObject.Click += new RoutedEventHandler(AssociatedObject_Click);
31 }
32 }
33
34 private void AssociatedObject_Click(object sender, RoutedEventArgs e)
35 {
36 if (AttachedTextBox != null && !string.IsNullOrEmpty(AttachedTextBox.Text))
37 {
38 if (IsDelete)
39 {
40 int index = 0;
41 if (AttachedTextBox.IsFocused)
42 {
43 index = AttachedTextBox.SelectionStart;
44 }
45 else
46 {
47 index = AttachedTextBox.Text.Length;
48 }
49 AttachedTextBox.Focus();
50 AttachedTextBox.Select(index, 0);
51 System.Windows.Forms.SendKeys.SendWait("{BACKSPACE}");
52 }
53 else
54 {
55 AttachedTextBox.Text = string.Empty;
56 }
57 }
58 }
59
60 protected override void OnDetaching()
61 {
62 base.OnDetaching();
63 }
64 }
65 }



posted on 2011-12-17 11:36  Damon-Cui  阅读(237)  评论(0编辑  收藏  举报