【发布时间】:2019-07-08 18:00:01
【问题描述】:
我的 UserControl 中有一个 DependencyProperty 属性更改回调。该属性按预期工作,回调按预期工作。
public double CurrentFlow
{
get { return (double)GetValue(CurrentFlowProperty); }
set { SetValue(CurrentFlowProperty, value); }
}
public static readonly DependencyProperty CurrentFlowProperty = DependencyProperty.Register("CurrentFlow", typeof(double), typeof(MyUserControl), new PropertyMetadata(0.0, OnCurrentFlowPropertyChanged));
private static void OnCurrentFlowPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
Console.WriteLine("CurrentFlow changed.");
}
但是,我的 UserControl 中有一个 TextBlock,我想在其中将 CurrentFlow 显示为格式化字符串。目前,我将 TextBlock 的 Text 属性绑定到 CurrentFlow,它可以工作,但我没有得到我需要的格式。 (小数点后的数字太多。)
<TextBlock Text="{Binding Path=CurrentFlow, RelativeSource={RelativeSource AncestorType=UserControl}}" />
理想情况下,我希望有一个名为 CurrentFlowString 的属性,它从 CurrentFlow 中获取值并将其格式化为我想要的格式。例如:CurrentFlow.ToString("0.00");
使用 DependencyProperties 解决此问题的最佳方法是什么?我知道如何使用常规属性执行此操作,但我有点卡在这里。
谢谢!
【问题讨论】:
-
StringFormat={0:F2}绑定应该可以工作。 -
StringFormat=0.00 和 StringFormat=0 工作,似乎做我想做的事。花括号是否仅对某些类型的格式是必需的?
标签: wpf properties