4

我不知道为什么,但是从类似的问题中,没有一个解决方案对我正常工作。

我意识到 aTextBox有一个属性 ( CharacterCasing),可以将其设置为Upper将任何小写字母更改为大写字母。它之所以如此出色,是因为用户在打字时永远不会被打断,大写锁定和移位不会对其产生负面影响,并且其他非字母字符也不会受到负面影响。

问题是没有选项可以将此属性用于组合框。来自类似帖子的解决方案似乎对我不起作用。我正在寻找复制 CharacterCasing 属性但对于 ComboBox。我不介意它是一个附属财产,事实上,那会很棒。我直接在 xaml 对象上尝试了几个不同的事件,但没有成功。

4

1 回答 1

15

ComboBox模板使用whenTextBoxIsEditabletrue。因此,您可以替换要在 上设置的模板CharacterCasingTextBox或者创建一个附加属性,该属性将TextBox通过其名称(“PART_EditableTextBox”)找到并在其上设置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);
        }
    }

}

以下是如何使用它:

    <ComboBox ItemsSource="{Binding Items}"
              IsEditable="True"
              local:ComboBoxBehavior.CharacterCasing="Upper">
        ...
于 2010-10-15T19:12:57.683 回答