我有一个文本框,有文本绑定:
<TextBox x:Name="textBox" Text="{Binding SomeText}" />
是否有办法以某种方式更改代码中的文本,使其可以撤消。
我能想到的唯一方法是ClipBoard和textBox.Paste(),但不想在用户有东西的情况下更改剪贴板。
这是一个看起来像这样的控件:
按钮会更改文本,我希望它可以撤消。
答案 0 :(得分:1)
这对我有用:
XAML:
<UserControl x:Class="TextboxButton.theControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Vertical">
<TextBox x:Name="textBox"/>
<Button Content="Push me to set textbox text" Click="Button_Click"/>
</StackPanel>
代码隐藏中的
:
public partial class theControl : UserControl
{
public theControl()
{
InitializeComponent();
}
public string TextToSet
{
get { return (string)GetValue(TextToSetProperty); }
set { SetValue(TextToSetProperty, value); }
}
public static DependencyProperty TextToSetProperty = DependencyProperty.Register("TextToSet", typeof(string), typeof(MainWindow), null);
private void Button_Click(object sender, RoutedEventArgs e)
{
textBox.SelectAll();
textBox.SelectedText = TextToSet;
}
}
使用它时,将TextToSet属性设置为按钮单击应提供的任何内容。
答案 1 :(得分:0)
当子类化它更清洁时:
this.BeginChange();
this.SetCurrentValue(TextProperty, text);
this.EndChange();