这有点难以解释,所以请多多包涵。在用户将测量值输入到提供的文本框中后,我在屏幕上显示了测量值。现在,我已经拥有了,因此该数字仅在输入时显示出来,这很棒。唯一的是,单位(厘米,毫米..)永久停留在画布上,我希望仅在输入数字时才会显示。我希望这是有道理的。
文本框代码:
<TreeViewItem Grid.Row="1" FontSize="12" Header="Width"/>
<TextBox Text="{Binding xcoord, UpdateSourceTrigger=PropertyChanged}" Name="x" Height="20" Width="40" Grid.Row="1" Grid.Column="2" />
<TreeViewItem Grid.Row="2" FontSize="12" Header="Height"/>
<TextBox Text="{Binding ycoord, UpdateSourceTrigger=PropertyChanged}" Name="y" Height="20" Width="40" Grid.Row="2" Grid.Column="2"/>
标签代码:
<!--height label appears on screen when value is entered-->
<Label Foreground="SteelBlue" FontWeight="Bold" HorizontalAlignment="Center" VerticalContentAlignment="Center" Height="40" Background="Transparent" x:Name="label2" FontSize="16" Width="60" Content="{Binding Text, ElementName=y}" ContentStringFormat=" {0} mm" Canvas.Left="527" Canvas.Top="162" RenderTransformOrigin="1.045,-0.141" VerticalAlignment="Top"></Label>
<!--width label appears on screen when a value is entered-->
<Label Foreground="SteelBlue" FontWeight="Bold" HorizontalAlignment="Center" VerticalContentAlignment="Center" Height="40" Background="Transparent" x:Name="label1" FontSize="16" Width="160" Content="{Binding Text, ElementName=x}" ContentStringFormat=" {0} mm" Canvas.Left="220" Canvas.Top="382" RenderTransformOrigin="1.045,-0.141" VerticalAlignment="Top"></Label>
答案 0 :(得分:1)
您可以使用IValueConverter,使用它可以将值转换为任何类型的输出并显示该值。在您的示例中,它看起来像这样:
public class UnitValueConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string text = value as string;
string unit = parameter as string;
if (!string.IsNullOrWhiteSpace(text))
{
return $"{text}{unit}";
}
else
{
return text;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
然后您可以在XAML代码中使用此IValueConverter,例如this。作为ConverterParameter,您需要传递单位字符串。