I have expanded Alex Klaus' solution to prevent typing too long texts.
public class TextBoxMaxLengthBehavior : Behavior<TextBox> { public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.Register( nameof(MaxLength), typeof(int), typeof(TextBoxMaxLengthBehavior), new FrameworkPropertyMetadata(0)); public int MaxLength { get { return (int) GetValue(MaxLengthProperty); } set { SetValue(MaxLengthProperty, value); } } public static readonly DependencyProperty LengthEncodingProperty = DependencyProperty.Register( nameof(LengthEncoding), typeof(Encoding), typeof(TextBoxMaxLengthBehavior), new FrameworkPropertyMetadata(Encoding.Default)); public Encoding LengthEncoding { get { return (Encoding) GetValue(LengthEncodingProperty); } set { SetValue(LengthEncodingProperty, value); } } protected override void OnAttached() { base.OnAttached(); AssociatedObject.PreviewTextInput += PreviewTextInputHandler; DataObject.AddPastingHandler(AssociatedObject, PastingHandler); } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PreviewTextInput -= PreviewTextInputHandler; DataObject.RemovePastingHandler(AssociatedObject, PastingHandler); } private void PreviewTextInputHandler(object sender, TextCompositionEventArgs e) { string text; if (AssociatedObject.Text.Length < AssociatedObject.CaretIndex) text = AssociatedObject.Text; else {
In XAML, I can use it as follows:
<DataTemplate DataType="{x:Type vm:StringViewModel}"> <TextBox Text="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"> <i:Interaction.Behaviors> <b:TextBoxMaxLengthBehavior MaxLength="{Binding MaxLength}" LengthEncoding="{Binding LengthEncoding}" /> </i:Interaction.Behaviors> </TextBox> </DataTemplate>
where xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" . Hope this helps someone else.
source share