[英]How to programatically set the binding of a textbox with stringformat?
[英]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)。 這是添加后保持光標在同一個地方的一個結果,
間2
和3
由.NET格式化。
如何將StringFormat與UpdateSourceTrigger一起設置為PropertyChanged?
注意:這只發生在.NET 4中。
通常,您不希望UpdateSourceTrigger
在TextBox.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.