簡體   English   中英

WPF:具有最小值的文本框和滑塊

[英]WPF: Textbox + Slider with min values

我有一個綁定到滑塊的文本框,並且滑塊設置了最小值。

問題是,如果我開始在文本框中輸入超出最小值的值,則這些值會自動傳輸到最小值。 例如,如果我將最小值設置為4,並且我想輸入12,則一旦按1,它已經在文本框中更改為4,而我不能輸入12,而是42。如果我開始輸入4或5(例如42或51等)就可以了。

有沒有辦法推遲對min的檢查,直到用戶按下enter鍵?

這是XAML:

<TextBox Text="{Binding ElementName=maxValue, Path=Value, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center" VerticalContentAlignment="Center" Width="30" Height="25" BorderBrush="Transparent"></TextBox>
<Slider Value="{Binding TotalSize}" Maximum="{Binding MaxMaxBackupSize}" Minimum="{Binding MinBackupSize}" TickPlacement="BottomRight" TickFrequency="2" IsSnapToTickEnabled="True" Name="maxValue"></Slider>

UpdateSourceTrigger屬性設置為LostFocus並按TAB

<TextBox Text="{Binding ElementName=maxValue, Path=Value, UpdateSourceTrigger=LostFocus}" TextAlignment="Center" VerticalContentAlignment="Center" Width="30" Height="25" BorderBrush="Transparent"></TextBox>

或按ENTER鍵並按如下方式處理PreviewKeyDown事件:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        e.Handled = true;
        TextBox textBox = sender as TextBox;
        textBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
    }
}

或者,您可以按照@Clemens的建議顯式更新source屬性:

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        e.Handled = true;
        TextBox textBox = sender as TextBox;
        BindingExpression be = textBox.GetBindingExpression(TextBox.TextProperty);
        be.UpdateSource();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM