I have this XAML code that works like a charm:
<TextBox Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding MyOwnCommand}" CommandParameter="{Binding MyTextProperty}" Key="Enter" />
</TextBox.InputBindings>
</TextBox>
There I have MyTextProperty
that is passed as parameter to MyOwnCommand
when I press enter key.
I do not want MyTextProperty
updates every time I type a letter (because it has some logic asociated), but I do want it executes once I finish typing (without pressing enter key or losing the focus). The ideal solution would be this:
<TextBox Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged, Delay=400}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding MyOwnCommand}" CommandParameter="{Binding MyTextProperty}" Key="Enter" />
</TextBox.InputBindings>
</TextBox>
The point here is the "Delay=400"
parameter. It waits until I finish typing and then updates MyTextProperty
.
But the problem I found at this point is that if I type something and immediately press enter, MyOwnCommand
is called but MyTextProperty
is not updated yet (it will be updated 400ms later).
I have tried to add the same delay in CommandParameter="{Binding MyTextProperty, Delay=400}"
, but it does not work.
What is the right approach to pass the CommandParameter once MyTextProperty
has been updated?
CodePudding user response:
TextBox.Text changes immediately after user types symbol from keyboard, even if there is a delay to send value to bound property. So you can bind CommandParameter to TextBox.Text directly:
<TextBox Name="MyTextBox"
Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged, Delay=400}">
<TextBox.InputBindings>
<KeyBinding Command="{Binding MyOwnCommand}"
CommandParameter="{Binding Text, ElementName=MyTextBox}"
Key="Enter" />
</TextBox.InputBindings>
</TextBox>
CodePudding user response:
but I do want it executes once I finish typing
I would split out this property into different properties. Then only have the enter Command extract the final value, set in the final property and excecute the final step.
// bound to the active textbox, which receives character by character changes
public string MyTextProperty { get { ... }
set { ...do individual key press logic here... }
public string MyTextProperty_Final { }
public void EnterCommand()
{
MyTextProperty_Final = MyTextProperty;
FinalOperationCommand(MyTextProperty_Final); // Or FinalOperationCommand.Invoke(MyTextProperty_Final);
}
public void FinalOperationCommand(string text)
{
... delay if needed ...
... Do stuff with MyTextProperty_Final
}