在WPF程序设计时,若使用Label
控件绑定数据后StringFormat
进行格式化显示时发现设定的StringFormat
无效,但TextBlock
控件中使用StringFormat
显示正常,导致Label
控件StringFormat
失败的根本原因在于Label
控件的Content
属性是一个object
对象,Binding.StringFormat
仅作用于string
类型属性。
若需要对Label
的Content
进行格式化显示,需要使用ContentStringFormat
属性来进行单独设置,示例如下:
<Label Content="{Binding Path=MaxLevelofInvestment}" ContentStringFormat="Amount is {0}" />
示例程序
XAML
代码:
<Window x:Class="WpfApp5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp5"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" FontSize="24">
<Window.Resources>
<local:DataConext_MainWindow x:Key="DC"/>
</Window.Resources>
<Grid DataContext="{StaticResource DC}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding Width, StringFormat={}{0:F3} }"/>
<TextBlock Grid.Row="1" Text="{Binding Height, StringFormat={}{0:F2} }"/>
<Label Grid.Row="2" Content="{Binding Width}" ContentStringFormat="{}{0:F3}"/>
<Button Grid.Row="3" Content="Modify" Click="Button_Click"/>
</Grid>
</Window>
cs
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SAUtil;
namespace WpfApp5
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var dc = Resources["DC"] as DataConext_MainWindow;
dc.Height = 12.34556666f;
dc.Width = 12.34556666;
}
}
public class DataConext_MainWindow : ValidatableModel
{
#region Height
private float _Height = 0;
public float Height
{
get { return _Height; }
set
{
if (_Height == value) return;
_Height = value;
RaisePropertyChanged();
}
}
#endregion
#region Width
private double _Width = 0;
public double Width
{
get { return _Width; }
set
{
if (_Width == value) return;
_Width = value;
RaisePropertyChanged();
}
}
#endregion
}
}
运行效果
参考资料
https://rotadev.com/wpf-stringformat-on-label-content-dev/