C# 当文本框是否聚焦时,显示不同小数精度的最佳方法是什么?
我有控制权,被别人利用。它有一个绑定到十进制值的TexBox。由于精度可以变化,我使用dependencProperty和多重绑定来指定它。 文本框未聚焦时,数字应以指定精度显示,但聚焦时,应显示完整数字 例如:C# 当文本框是否聚焦时,显示不同小数精度的最佳方法是什么?,c#,wpf,C#,Wpf,我有控制权,被别人利用。它有一个绑定到十进制值的TexBox。由于精度可以变化,我使用dependencProperty和多重绑定来指定它。 文本框未聚焦时,数字应以指定精度显示,但聚焦时,应显示完整数字 例如: 精度:2 用户输入:29.333 未聚焦的文本框应显示:29.33 文本框应显示:29.333 我通过使用IMultibindingConverter和IsFocused属性实现了这一点。但我不知道这是否是最好的方法 我的文本框定义如下 <UserControl.Reso
- 精度:2
- 用户输入:29.333
- 未聚焦的文本框应显示:29.33
- 文本框应显示:29.333
<UserControl.Resources>
<conv:ValuePrecisionConverter x:Key="ValuePrecisionConverter" />
</UserControl.Resources>
<TextBox x:Name="myTextBox">
<TextBox.Text>
<MultiBinding Converter="{StaticResource ValuePrecisionConverter}" Mode="TwoWay"
NotifyOnValidationError="true">
<Binding ElementName="parent" UpdateSourceTrigger="PropertyChanged" Path="Value" Mode="TwoWay" />
<Binding ElementName="parent" Path="Precision"/>
<Binding ElementName="parent" Path="AdditionalFormatting"/>
<Binding ElementName="myTextBox" Path="IsFocused" Mode="OneWay"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
这是实现我需要的最好方法吗?可以这样使用IsFocused属性吗?尝试使用thisss
<TextBox x:Name="myTextBox">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="False">
<Setter Property="Text" Value="{Binding Value, StringFormat=n2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Text" Value="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
我希望您选择带有PreviewGotKeyboardFocus和PreviewLostKeyboardFocus的事件触发器。。。使用转换器设置该值。。这里不需要MuiltBinding…我的值的格式有不同的精度,这取决于使用我的控件的人。此外,它可能会添加一些特殊的格式。根据您的建议,我如何实现这一点?您可以使用动态值绑定StringFormat:StringFormat={binding…}或StringFormat={StaticResource…}。我不确定我是否理解你用转换器设置值的意思。我的精度取决于我的DependencyProperty精度的值。此外,我还必须使用附加格式(这是另一个依赖属性)应用一些自定义格式。我们将如何做到这一点?
<TextBox x:Name="myTextBox">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="IsFocused" Value="False">
<Setter Property="Text" Value="{Binding Value, StringFormat=n2, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Text" Value="{Binding Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>