WPF 文本框changed事件 急!!!!
发布网友
发布时间:2023-10-20 04:49
我来回答
共1个回答
热心网友
时间:2024-11-29 09:07
给你介绍两种方式
一种就是TextChanged事件,一种是依赖属性的回调方法。
效果如下:
XAML代码:
<StackPanel Orientation="Vertical">
<TextBox Height="50" TextChanged="TextBox_TextChanged"/>
<TextBox x:Name="txt1" Height="50" Text="{Binding MyText,UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
C#代码:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
}
/// <summary>
/// 方式1,事件方法
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
int i = 0;
if (int.TryParse((((TextBox)sender).Text), out i))
{
if (((TextBox)sender).Text != i.ToString())
{
((TextBox)sender).Text = i.ToString();
((TextBox)sender).SelectionStart = i.ToString().Length;
}
}
}
/// <summary>
/// 方式2,依赖属性方法
/// </summary>
public string MyText
{
get { return (string)GetValue(MyTextProperty); }
set { SetValue(MyTextProperty, value); }
}
public static readonly DependencyProperty MyTextProperty =
DependencyProperty.Register("MyText", typeof(string), typeof(MainWindow), new PropertyMetadata("1",new PropertyChangedCallback((d,e)=>((MainWindow)d).PropertyChanged())));
private void PropertyChanged()
{
int i = 0;
if (int.TryParse(MyText, out i))
{
if (MyText != i.ToString())
{
//用Dispatcher处理刷新
this.Dispatcher.BeginInvoke(new Action(delegate
{
MyText = i.ToString();
txt1.SelectionStart = i.ToString().Length;
}));
}
}
}
}