3

我有这个像魅力一样工作的 XAML 代码:

<TextBox Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding MyOwnCommand}" CommandParameter="{Binding MyTextProperty}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

当我按下回车键时,我将MyTextProperty其作为参数传递给。MyOwnCommand

我不希望MyTextProperty每次输入字母时都更新(因为它有一些相关的逻辑),但我确实希望它在我完成输入后执行(不按回车键或失去焦点)。理想的解决方案是:

<TextBox Text="{Binding MyTextProperty, UpdateSourceTrigger=PropertyChanged, Delay=400}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding MyOwnCommand}" CommandParameter="{Binding MyTextProperty}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

这里的重点是"Delay=400"参数。它等到我完成输入然后更新MyTextProperty

但此时我发现的问题是,如果我输入一些内容并立即按回车,MyOwnCommand会调用但MyTextProperty尚未更新(它将在 400 毫秒后更新)。

我试图在 中添加相同的延迟CommandParameter="{Binding MyTextProperty, Delay=400}",但它不起作用。

更新后传递 CommandParameter 的正确方法是MyTextProperty什么?

4

2 回答 2

3

TextBox.Text 在用户从键盘键入符号后立即更改,即使将值发送到绑定属性存在延迟。因此,您可以直接将 CommandParameter 绑定到 TextBox.Text:

<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>
于 2022-01-05T19:49:20.020 回答
0

但我确实希望它在我完成输入后执行

我会将这个属性拆分为不同的属性。然后只需输入命令提取最终值,在最终属性中设置并执行最后一步。


// 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
}

于 2022-01-05T20:13:46.067 回答