设置 tex 框只接受 1 个字母

Set tex box to accept only 1 letter

所以我有 TextBox 和命令:

<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>

命令

public void Execute(object parameter)
{

}

而且我希望我的 TextBox 只接受 1 latter 如果用户输入一些 latter 它会删除旧的并只显示最后一个。

这是我尝试过的:

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

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

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:

<TextBox Name="TextBoxLatter" Text="{Binding Text, UpdateSourceTrigger=PropertyChanged}"
         MaxLength="1"/>

您不需要 EventTrigger 或命令。