[英]XAML Binding with Delay and KeyBinding
我有這個 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}"
中添加相同的延遲,但它不起作用。
更新MyTextProperty
后傳遞 CommandParameter 的正確方法是什么?
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>
但我確實希望它在我完成輸入后執行
我會將這個屬性拆分為不同的屬性。 然后只需輸入命令提取最終值,在最終屬性中設置並執行最后一步。
// 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.