TextBlock: text binding and StringFormat

Is it possible to bind Text and StringFormat ?

 <TextBlock Text="{Binding Path=Price, StringFormat={Binding Path=DecimalPoints}}" /> 

Decimal points are constantly changing from F0 to F15 . Unfortunately, the code above does not compile.

+4
source share
3 answers

I think your best bet is definitely a converter. Then your binding will look like this:

 <TextBlock.Text> <MultiBinding Converter="{StaticResource StringFormatConverter }"> <Binding Path="Price"/> <Binding Path="DecimalPoints"/> </MultiBinding> </TextBlock.Text> 

Then a quick converter (you can do it better, but this is a general idea).

  public class StringFormatConverter : IMultiValueConverter { #region IMultiValueConverter Members public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { double number = (double)values[0]; string format = "f" + ((int)values[1]).ToString(); return number.ToString(format); } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion } 
+5
source

As @Sheridan mentioned, Binding will not work in this case. But you can create a class with static strings and access them in XAML. Syntax:

 <x:Static Member="prefix : typeName . staticMemberName" .../> 

The following is an example:

XAML

 xmlns:local="clr-namespace:YourNameSpace" xmlns:sys="clr-namespace:System;assembly=mscorlib" <Grid> <TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.DateFormat}}" HorizontalAlignment="Right" /> <TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}, StringFormat={x:Static Member=local:StringFormats.Time}}" /> </Grid> 

Code behind

 public class StringFormats { public static string DateFormat = "Date: {0:dddd}"; public static string Time = "Time: {0:HH:mm}"; } 

For more information see

x: Static Markup Extension on MSDN

+5
source

No, you cannot ... the reason is that you can only bind to DependencyProperty to DependencyObject , and the StringFormat property of the Binding class is just a string .

+2
source

Source: https://habr.com/ru/post/1499651/


All Articles