簡體   English   中英

使用TextBox上的StringFormat綁定到double

[英]Binding to a double with StringFormat on a TextBox

我正在使用WPF的TextBox,將Text屬性上的綁定設置為ViewModel上的double。

我的XAML看起來像這樣:

<TextBox Text="{Binding Path=MyDoubleValue, StringFormat=N2, UpdateSourceTrigger=PropertyChanged}" />

不幸的是,當我將UpdateSourceTrigger切換到PropertyChanged並輸入值12345 ,我得到12,354.00編輯 :注意4之前的5)。 這是添加后保持光標在同一個地方的一個結果,23由.NET格式化。

如何將StringFormat與UpdateSourceTrigger一起設置為PropertyChanged?

注意:這只發生在.NET 4中。

通常,您不希望UpdateSourceTriggerTextBox.Text綁定上成為PropertyChanged ,因為每次按下鍵時都會觸發Validation和Change通知。

如果你這樣做只是為了如果用戶點擊Enter它將在處理save命令之前保存該值,然后我建議掛鈎到PreviewKeyDown事件並手動更新源,如果按下的鍵是Enter(通常我做這個附屬物)

private void TextBox_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        var obj = sender as UIElement;
        BindingExpression textBinding = BindingOperations.GetBindingExpression(
            obj, TextBox.TextProperty);

        if (textBinding != null)
            textBinding.UpdateSource();
    }
}

但話雖如此,如果您仍想使用UpdateSourceTrigger=PropertyChanged ,則在顯示值時考慮使用格式,但在用戶編輯時將其刪除。

<TextBox>
    <TextBox.Style>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Text" Value="{Binding Path=MyDoubleValue, StringFormat=N2}" />
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Text" Value="{Binding Path=MyDoubleValue, UpdateSourceTrigger=PropertyChanged}" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

暫無
暫無

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

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