我必须实现 WPF TextBox,它将通过绑定提供修剪后的文本。乍一看,这项任务对我来说相当简单。我决定使用依赖属性值强制。下面我写了我的代码,但这似乎不起作用。我的绑定属性中没有修剪字符串。我究竟做错了什么?也许我应该采取另一种方法?
public class MyTextBox : TextBox
{
static MyTextBox()
{
TextProperty.OverrideMetadata(typeof(MyTextBox), new FrameworkPropertyMetadata(string.Empty, null, new CoerceValueCallback(CoerceText)));
}
private static object CoerceText(DependencyObject d, object basevalue)
{
string s = basevalue as string;
if(s != null)
{
return s.Trim();
}
else
{
return string.Empty;
}
}
}
我在我的应用程序中添加了简单的窗口进行测试。xml:
<Window x:Class="TextBoxDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:TextBoxDemo="clr-namespace:TextBoxDemo"
Title="MainWindow"
Width="525"
Height="350">
<Grid>
<TextBoxDemo:MyTextBox x:Name="textBox1"
Width="120"
Height="23"
Margin="55,73,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding Text}" />
<TextBoxDemo:MyTextBox x:Name="textBox2"
Width="120"
Height="23"
Margin="286,184,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Text="{Binding Text}" />
</Grid>
</Window>
和代码隐藏:
public partial class MainWindow : Window
{
private string _text;
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
public string Text
{
get { return _text; }
set
{
_text = value;
MessageBox.Show(string.Format("|{0}|", _text));
}
}
}