1个回答
2014-03-28 · 知道合伙人数码行家
关注
展开全部
给你介绍两种方式
一种就是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;
}));
}
}
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询