gpt4 book ai didi

WPF:强制大写的组合框?

转载 作者:行者123 更新时间:2023-12-04 22:16:30 26 4
gpt4 key购买 nike

我不知道为什么,但没有一个解决方案对我来说从 similar question 正常工作。

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

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

最佳答案

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

关于WPF:强制大写的组合框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3945221/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com