當IsEditable
爲真時,ComboBox
模板使用TextBox
。因此,您可以替換模板以在TextBox
上設置CharacterCasing
,或者創建一個附加屬性,該名稱將通過其名稱(「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">
...
這似乎並不爲我工作...是不是在用戶控制中可用?特別是'var textBox = comboBox.Template.FindName(「PART_EditableTextBox」,comboBox)作爲TextBox;'將textBox設置爲null,這就是'CharacterCasing'永遠不會被應用的原因。 – 2010-10-15 20:46:30
這很奇怪......我測試了它,它對我來說工作得很好。你是否將IsEditable設置爲true?如果它是錯誤的,ComboBox使用不同的模板,它不包含TextBox – 2010-10-15 22:45:24
我不知道它爲什麼不起作用。我在該行放置了一個調試停止並檢查了comboBox的屬性。 IsEditable被設置爲true。 – 2010-10-16 23:07:16