Tony
Tony

Reputation: 3638

WPF custom textblock layout

I'm new to WPF, and I'm wondering if it's possible to create a custom TextBlock so that a string can be rendered in a certain way.

So for any given string:

The list goes on, essentially I'm wondering if I create a custom TextBlock inheriting from TextBlock, can I override the default behaviour in some way?

Upvotes: 1

Views: 110

Answers (1)

D M
D M

Reputation: 7179

You could write a ValueConverter that transforms the contents of TextBlock.Text:

public class MyTextConverter : IValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        if (string.IsNullOrEmpty(values?[0]))
        {
            return string.Empty;
        }
            
        var manipulatedString = values[0] as string;
            
        // Do something with the string...
            
        return manipulatedString;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Then use the converter in your Window or UserControl:

MyNamespace.MyWindowClass.xaml.cs

public class MyWindowClass : Window
{
    public MyWindowClass() {}

    public MyTextProperty { get; set; }
}

MyNamespace.MyWindowClass.xaml

<Window
    x:Class="MyNamespace.MyWindowClass"
    xmlns:local="clr-namespace:MyNamespace"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"/>

    <Window.Resources>
        <local:MyTextConverter x:Key="myTextConverterInstance"/>
    </Window.Resources>

    <!-- ... -->
    <TextBlock Text="{Binding MyTextProperty, 
                     Converter={StaticResource myTextConverterInstance}}"/>
    <!-- ... -->
</Window>

Upvotes: 4

Related Questions