Wpf 将文本框设置为仅接受1个字母

Wpf 将文本框设置为仅接受1个字母,wpf,textbox,Wpf,Textbox,所以我有文本框和命令: <TextBox Name="TextBoxLatter"> <i:Interaction.Triggers> <i:EventTrigger EventName="TextChanged"> <i:InvokeCommandAction Command="{Binding Path=TextBoxKeyDownCommand}"

所以我有文本框和命令:

<TextBox Name="TextBoxLatter">
    <i:Interaction.Triggers>
          <i:EventTrigger EventName="TextChanged">
               <i:InvokeCommandAction Command="{Binding Path=TextBoxKeyDownCommand}"
                                      CommandParameter="{Binding ElementName=TextBoxLatter, Path=Text}"/>
           </i:EventTrigger>
  </i:Interaction.Triggers>
</TextBox>
我希望我的文本框只接受1个后者,如果用户键入后面的某个,它将删除旧文本框并仅显示最后一个文本框

这就是我所尝试的:

public void Execute(object parameter)
{
    TextBox textBox = parameter as TextBox;
    if (textBox != null)
    {
        string str = textBox.Text;
        textBox.Text = "";
        textBox.Text = str;
    }
}

将对TextBox控件的引用传递给视图模型中的命令会破坏MVVM模式。应将文本绑定到源属性:

private string _text;
public string Text
{
    get { return _text; }
    set
    {
        if (value == null || value.Length == 0)
        {
            _text = string.Empty;
        }
        else
        {
            char last = value.Last();
            _text = last.ToString();
        }
        RaisePropertyChanged();
    }
}
XAML:

您不需要EventTrigger或命令

private string _text;
public string Text
{
    get { return _text; }
    set
    {
        if (value == null || value.Length == 0)
        {
            _text = string.Empty;
        }
        else
        {
            char last = value.Last();
            _text = last.ToString();
        }
        RaisePropertyChanged();
    }
}
<TextBox Name="TextBoxLatter" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
         MaxLength="1"/>