WPF:Combobox强制大写?

时间:2010-10-15 18:57:38

标签: wpf combobox uppercase

我不确定原因,但是similar question没有一个解决方案适合我。

我意识到TextBox有一个属性(CharacterCasing),可以将其设置为Upper以将任何小写输入更改为大写。它的工作原理非常好,因为用户在键入时不会被打断,大写锁定和移位不会对其产生负面影响,其他非字母字符也不会受到负面影响。

问题是没有选项可以将此属性用于ComboBox。这个类似帖子的解决方案对我来说似乎不起作用。我想复制CharacterCasing属性,但对于ComboBox。我不介意它是一个附属财产,事实上,这是伟大的。我直接在xaml对象上尝试了几个不同的事件,没有成功。

1 个答案:

答案 0 :(得分:13)

ComboBox为真时,TextBox模板使用IsEditable。因此,您可以替换模板以在CharacterCasing上设置TextBox,或者创建一个附加属性,该属性将通过其名称(“PART_EditableTextBox”)找到TextBox并设置{{1它上面的属性。

以下是附加属性解决方案的简单实现:

CharacterCasing

以下是如何使用它:

public static class ComboBoxBehavior
{

    [AttachedPropertyBrowsableForType(typeof(ComboBox))]
    public static CharacterCasing GetCharacterCasing(ComboBox comboBox)
    {
        return (CharacterCasing)comboBox.GetValue(CharacterCasingProperty);
    }

    public static void SetCharacterCasing(ComboBox comboBox, CharacterCasing value)
    {
        comboBox.SetValue(CharacterCasingProperty, value);
    }

    // Using a DependencyProperty as the backing store for CharacterCasing.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CharacterCasingProperty =
        DependencyProperty.RegisterAttached(
            "CharacterCasing",
            typeof(CharacterCasing),
            typeof(ComboBoxBehavior),
            new UIPropertyMetadata(
                CharacterCasing.Normal,
                OnCharacterCasingChanged));

    private static void OnCharacterCasingChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
    {
        var comboBox = o as ComboBox;
        if (comboBox == null)
            return;

        if (comboBox.IsLoaded)
        {
            ApplyCharacterCasing(comboBox);
        }
        else
        {
            // To avoid multiple event subscription
            comboBox.Loaded -= new RoutedEventHandler(comboBox_Loaded);
            comboBox.Loaded += new RoutedEventHandler(comboBox_Loaded);
        }
    }

    private static void comboBox_Loaded(object sender, RoutedEventArgs e)
    {
        var comboBox = sender as ComboBox;
        if (comboBox == null)
            return;

        ApplyCharacterCasing(comboBox);
        comboBox.Loaded -= comboBox_Loaded;
    }

    private static void ApplyCharacterCasing(ComboBox comboBox)
    {
        var textBox = comboBox.Template.FindName("PART_EditableTextBox", comboBox) as TextBox;
        if (textBox != null)
        {
            textBox.CharacterCasing = GetCharacterCasing(comboBox);
        }
    }

}