我希望能够在运行时更改只读数据的显示格式。我发现Label有ContentStringFormat属性。我将ContentStringFormat绑定到DependencyProperty,但是当我更改它时,Label的内容不会改变。
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="Window">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Label Grid.Row="0" x:Name="Label" ContentStringFormat="{Binding ElementName=Window,
Path=StringFormat, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
<StackPanel Orientation="Horizontal" Grid.Row="2">
<Button Content="Add accuracy" Click="ButtonAdd_OnClick"/>
<Button Content="Reduce accuracy" Click="ButtonReduce_OnClick"/>
</StackPanel>
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;
using System.Windows.Controls;
using TestApp.Annotations;
namespace TestApp
{
public partial class MainWindow : Window, INotifyPropertyChanged
{
public static readonly DependencyProperty StringFormatProperty = DependencyProperty.Register("StringFormat", typeof(string), typeof(Label),
new PropertyMetadata(null));
public string StringFormat
{
get { return (string)GetValue(StringFormatProperty); }
set { SetValue(StringFormatProperty, value); }
}
public MainWindow()
{
InitializeComponent();
Label.Content = 10m;
StringFormat = "f2";
OnPropertyChanged("StringFormat");
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private void ButtonAdd_OnClick(object sender, RoutedEventArgs e)
{
var num = int.Parse(StringFormat.Substring(1));
StringFormat = "f" + (num + 1);
}
private void ButtonReduce_OnClick(object sender, RoutedEventArgs e)
{
var num = int.Parse(StringFormat.Substring(1));
if(num<=0)
return;
StringFormat = "f" + (num - 1);
}
}
}