gpt4 book ai didi

wpf - 如何在 WPF 中设置组合框的最大长度?

转载 作者:行者123 更新时间:2023-12-03 21:16:14 26 4
gpt4 key购买 nike

我如何将 maxlength 设置为组合框,它应用了一种样式。

谢谢

最佳答案

使用 DependencyProperty 时,我们可以在不修改样式/模板的情况下设置组合框的最大长度。

public class EditableComboBox
{

public static int GetMaxLength(DependencyObject obj)
{
return (int)obj.GetValue(MaxLengthProperty);
}

public static void SetMaxLength(DependencyObject obj, int value)
{
obj.SetValue(MaxLengthProperty, value);
}

// Using a DependencyProperty as the backing store for MaxLength. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached("MaxLength", typeof(int), typeof(EditableComboBox), new UIPropertyMetadata(OnMaxLenghtChanged));

private static void OnMaxLenghtChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
var comboBox = obj as ComboBox;
if (comboBox == null) return;

comboBox.Loaded +=
(s, e) =>
{
var textBox = comboBox.FindChild(typeof(TextBox), "PART_EditableTextBox");
if (textBox == null) return;

textBox.SetValue(TextBox.MaxLengthProperty, args.NewValue);
};
}
}

用法示例:
<ComboBox ComboboxHelper:EditableComboBox.MaxLength="50" />

ComboboxHelper 在哪里:

xmlns:ComboboxHelper="clr-namespace:yourNameSpace;assembly=yourAssembly"



组合框.FindChild(...) 方法贴 here .

关于wpf - 如何在 WPF 中设置组合框的最大长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1572887/

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