u盘format命令无效
()
在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/