Use StringFormat to add a string to a WPF XAML binding
Your first example is effectively what you need:
<TextBlock Text="{Binding CelsiusTemp, StringFormat={}{0}°C}" />
StringFormat on Binding
The best and the easiest way would be to use a converter to which you pass the Date and get the formatted string back. In e.g. MyNamespace.Converters
namespace:
public class DateFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
DateTime dt = DateTime.Parse(value.ToString());
return dt.ToString("dd/MM/yyyy");
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
And in your xaml just reference the converter and add the following converter:
xmlns:conv="using:MyNamespace.Converters"
in your xaml page and in page.resources add this
<conv:DateFormatConverter x:Name="DateToStringFormatConverter"/>
<TextBlock Text="{Binding Date, Converter={StaticResource DateToStringFormatConverter}"/>
String format for binding text in WPF
Here are two ways you can do it, one with a converter and one without.
"Text1" and "Text2" in the bindings are properties of the DataContext.
You will need to change the "MainText" to be a property:
public static string MainText { get; set; } = "Test: {0} Test2: {1}";
Without a converter:
<Label>
<Label.Content>
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{x:Static local:MainWindow.MainText}">
<Binding Path="Text1" />
<Binding Path="Text2" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Label.Content>
</Label>
With a converter:
<Label>
<Label.Resources>
<local:TextFormatConverter x:Key="TextFormatConverter" />
</Label.Resources>
<Label.Content>
<MultiBinding Converter="{StaticResource TextFormatConverter}" ConverterParameter="{x:Static local:MainWindow.MainText}">
<Binding Path="Text1" />
<Binding Path="Text2" />
</MultiBinding>
</Label.Content>
</Label>
And the converter:
public class TextFormatConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string fmt = parameter as string;
if (!string.IsNullOrWhiteSpace(fmt))
return string.Format(fmt, values);
return null;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Binding String Format
You cannot bind StringFormat at all. StringFromat is not dependency property and therefore it is not bindable. If you want to achive this you have to do it in code behind or in case you use a MVVM pattern yu should do it in the view model. You can alo try this solution which uses MultiBinding. See this link.
xaml specific StringFormat Binding
You simply need to append ' EUR' to the StringFormat
.
Text="{Binding MyProp, StringFormat={}{0:N2} EUR}"
To add the converter culture to get commas instead of periods, again you can add EUR to the format string.
Text="{Binding MyProp, StringFormat={}{0:N2} EUR, ConverterCulture=de-DE}"
Add newline to Stringformat in XAML
Set the TextBlock's Inlines
property:
<TextBlock DataContext="{Binding DataContext.Week.Days[1].Date,
RelativeSource={RelativeSource AncestorType=DataGrid}}">
<Run Text="{Binding Mode=OneWay, StringFormat=ddd}"/>
<LineBreak/>
<Run Text="{Binding Mode=OneWay, StringFormat=dd.MM.yyyy}"/>
</TextBlock>
StringFormat in XAML
It seems that, similar to Binding
in WinRT, Binding
in Windows Phone Universal Apps doesn't have StringFormat
property. One possible way to work around this limitation is using Converter
as explained in this blog post,
To summarize the post, you can create an IValueConverter
implmentation that accept string format as parameter :
public sealed class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format((string)parameter, value);
}
public object ConvertBack(object value, Type targetType, object parameter,
string language)
{
throw new NotImplementedException();
}
}
Create a resource of above converter in your XAML, then you can use it like this for example :
<TextBlock x:Name="countTextBlock"
Text="{Binding Count,
Converter={StaticResource StringFormatConverter},
ConverterParameter='{}{0:n}'}" />
Binding StringFormat
Since BindingBase.StringFormat
is not a dependency property, I do not think that you can bind it. If the formatting string varies, I'm afraid you will have to resort to something like this
<TextBlock Text="{Binding MyFormattedProperty}" />
and do the formatting in your view model. Alternatively, you could use a MultiBinding and a converter (example code untested):
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myStringFormatter}">
<Binding Path="MyProperty" />
<Binding Path="MyFormatString" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
public class StringFormatter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return string.Format((string)values[1], values[0]);
}
...
}
Related Topics
Use Dependency Injection in Static Class
C# Winforms: How to Set Main Function Stathreadattribute
C# Wait for User to Finish Typing in a Text Box
How to Optionally Turn Off the JSONignore Attribute at Runtime
Using Tfs API, How to Find the Comments Which Were Made on a Code Review
Interesting "Params of Ref" Feature, Any Workarounds
Does Using Parameterized SQLcommand Make My Program Immune to SQL Injection
Working with Incredibly Large Numbers in .Net
How to Include Other Files to the Output Directory in C# Upon Build
How to Retrieve Disk Information in C#
Xdocument: Saving Xml to File Without Bom
Parent Control Mouse Enter/Leave Events with Child Controls
How to Read/Stream a File Without Loading the Entire File into Memory
How to Set a Conditional Compile Variable
ASP.NET Web Application Message Box
Difference Between System.Datetime.Now and System.Datetime.Today