请参阅以下示例:
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
SizeToContent="WidthAndHeight">
<Window.DataContext>
<src:CodeName/>
</Window.DataContext>
<TextBox Text="{Binding Code, UpdateSourceTrigger=PropertyChanged}" />
</Window>
Imports System.ComponentModel
Public Class CodeName
Implements INotifyPropertyChanged
Private m_Code As String
Public Property Code() As String
Get
Return m_Code
End Get
Set(ByVal value As String)
If Not String.IsNullOrWhiteSpace(value) Then value = "_" & value
m_Code = value
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs("Code"))
End Set
End Property
Public Event PropertyChanged(ByVal sender As Object,
ByVal e As PropertyChangedEventArgs) _
Implements INotifyPropertyChanged.PropertyChanged
End Class
正如您所看到的,我正在更改已修改的值,以便当用户在TextBox
中输入文字时,会更新_
到其开头。
当我输入123456789
时,TextBox
中的结果是:_________987654321
而不是_________123456789
正如预期的那样。
什么可以是一个简洁的方法来解决它?
我不希望我的整个代码变脏,KeyUp等事件会移动插入符号。
另一方面,我确实希望在实体层面完成此任务。
注意:我的“真实”功能是使用破折号等格式化手机号码。
答案 0 :(得分:0)
我会使用文本框的textchanged事件将插入符号移到最后,如下所示:
<TextBox Name="textBox1" Text="{Binding Code, UpdateSourceTrigger=PropertyChanged}" TextChanged="textChangedEventHandler"/>
Private Sub textChangedEventHandler(ByVal sender As Object, ByVal args As TextChangedEventArgs)
textBox1.CaretIndex = textBox1.Text.Length
End Sub
答案 1 :(得分:0)
Public Class TextBoxBehavor
Public Shared Function GetMoveCaretOnTextChange(ByVal element As TextBox) As Boolean
If element Is Nothing Then Throw New ArgumentNullException("element")
Return element.GetValue(MoveCaretOnTextChangeProperty)
End Function
Public Shared Sub SetMoveCaretOnTextChange(ByVal element As TextBox, ByVal value As Boolean)
If element Is Nothing Then Throw New ArgumentNullException("element")
element.SetValue(MoveCaretOnTextChangeProperty, value)
End Sub
Public Shared ReadOnly MoveCaretOnTextChangeProperty As DependencyProperty =
DependencyProperty.RegisterAttached("MoveCaretOnTextChange",
GetType(Boolean), GetType(TextBoxBehavior),
New FrameworkPropertyMetadata(
New PropertyChangedCallback(AddressOf MoveCaretOnTextChange_PropertyChanged)))
Private Shared Sub MoveCaretOnTextChange_PropertyChanged(ByVal sender As Object,
ByVal e As DependencyPropertyChangedEventArgs)
Dim tb = DirectCast(sender, TextBox)
Static tb_TextChanged As TextChangedEventHandler =
Sub(obj, tcea)
Dim textBox = DirectCast(obj, TextBox)
textBox.CaretIndex = textBox.Text.Length
End Sub
If CBool(e.NewValue) Then
AddHandler tb.TextChanged, tb_TextChanged
Else
RemoveHandler tb.TextChanged, tb_TextChanged
End If
End Sub
End Class
用法:
<TextBox src:TextBoxBehavior.MoveCaretOnTextChange="True"
xmlns:src="clr-namespace:WpfApplication1" />