Reputation: 571
I use C# and WPF and MVVM
I have an editable Combobox so that a user can not only select items from the list but also type own text in the comboxbox' textfield
XAML:
<br>
<ComboBox IsEditable="True"<br>
IsTextSearchEnabled="True" <br>
IsTextSearchCaseSensitive="False"<br>
StaysOpenOnEdit="True"<br>
Text="{Binding TextEntered}"<br>
</ComboBox>
<br>
In the bound property "TextEntered" I can see in the Debugger the text that the user has typed - however this does not work if the user presses ENTER to finished his input. So how could I react when the users presses Enter ?
thank you
Upvotes: 3
Views: 1993
Reputation: 169190
You could handle the PreviewKeyDown
event, for example using an attached behaviour:
public class EnterBehavior
{
public static ICommand GetCommand(UIElement element)
{
return (ICommand)element.GetValue(CommandProperty);
}
public static void SetCommand(UIElement element, ICommand value)
{
element.SetValue(CommandProperty, value);
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.RegisterAttached(
"Command",
typeof(ICommand),
typeof(EnterBehavior),
new PropertyMetadata(OnCommandChanged));
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
UIElement element = (UIElement)d;
element.PreviewKeyDown += (ss, ee) =>
{
if (ee.Key == Key.Enter)
{
GetCommand(element)?.Execute(null);
}
};
}
}
Sample usage:
<ComboBox IsEditable="True"
local:EnterBehavior.Command="{Binding YourCommandProperty}" ... />
Upvotes: 1
Reputation: 711
If you don't want to react on PropertyChanged, you can set the UpdateSourceTrigger to Explicit
<ComboBox IsEditable="True"
IsTextSearchEnabled="True"
IsTextSearchCaseSensitive="False"
StaysOpenOnEdit="True"
Text="{Binding TextEntered, UpdateSourceTrigger=Explicit}">
<ComboBox.InputBindings>
<KeyBinding Gesture="Enter"
Command="{Binding UpdateBindingOnEnterCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ComboBox}}}"></KeyBinding>
</ComboBox.InputBindings>
And call UpdateSource of the binding in the execute of your command
public class UpdateBindingOnEnterCommand : ICommand
{
...
public void Execute(object parameter)
{
if (parameter is ComboBox control)
{
var prop = ComboBox.TextProperty;
var binding = BindingOperations.GetBindingExpression(control, prop);
binding?.UpdateSource();
}
}
...
}
Upvotes: 2