我有一个像这样的ComboBox:
<ComboBox IsEditable="True"
ItemsSource="{Binding SelectableValues}"
SelectedValue="{Binding SelectedValue}" />
SelectableValues
是double
的列表,SelectedValue
是double
。如果用户从列表中选择值或手动输入其中一个值,则会更新SelectedValue
属性。但是,如果用户手动输入另一个值,则不是。如何允许SelectedValue
采用除ItemsSource
以外的其他值?
编辑:将其想象为MS Word中的字体大小框。我可以从列表中选择一个值,或者提供我自己的值。
答案 0 :(得分:1)
创建继承comboBox的用户控件。将依赖项属性添加为“SelectedText”。在组合框上为LostFocus创建事件处理程序,在事件处理程序中分配输入的值依赖项属性'SelectedText'。 对'SelectedText'进行绑定,在其setter中如果value为new,则ad为collection,并将SelectedValue设置为new。
间接地,您必须通过在ComboBox中添加新属性来更新源。
public class ExtendedComboBox : ComboBox
{
public ExtendedComboBox()
{
this.IsEditable = true;
this.LostFocus += ComboBox_LostFocus;
}
public string SelectedText
{
get
{
return (string)GetValue(SelectedTextProperty);
}
set
{
SetValue(SelectedTextProperty, value);
}
}
public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register("SelectedText", typeof(string), typeof(ExtendedComboBox), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnSelectedTextPropertyChanged)));
private static void OnSelectedTextPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
{
}
private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
{
SelectedText = (e.Source as ComboBox).Text??string.Empty;
}
}
// Binding Example
%gt%local:ExtendedComboBox Margin="3" x:Name="ecb" SelectedText="{Binding SelectedText,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding SelectedTextList}">%gt/local:ExtendedComboBox>