Question

When binding with Wpf is there a way to use System.String funcntions without using converters?

<TextBlock Text="({Binding Path=Text}).Trim()"/>

that's basically my desire.

Was it helpful?

Solution

I would use a converter.

Binding Xaml

<StackPanel>
  <StackPanel.Resources>
    <local:StringTrimmingConverter x:Key="trimmingConverter" />
  <StackPanel.Resources>
  <TextBlock Text="{Binding Path=Text, Converter={StaticResource trimmingConverter}}" />
</StackPanel>

StringTrimmingConverter.cs

using System;
using System.Windows.Data;

namespace WpfApplication1
{
    [ValueConversion(typeof(string), typeof(string))]
    public class StringTrimmingConverter : IValueConverter
    {
        #region IValueConverter Members
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value.ToString().Trim();
        }
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }
        #endregion
    }
}

And if VB StringTrimmingConverter.vb

Imports System.Globalization

Public Class StringTrimmingConverter
    Implements IValueConverter

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
        Return value.ToString().Trim
    End Function

    Public Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert
        Return value
    End Function

End Class

OTHER TIPS

I created an ultimate converter for all the functions in System.String, needs some improvement would love to hear from you, hope to update it in future, please accept:

VB:

<ValueConversion(GetType(String), GetType(Object))> _
Class StringFunctions : Implements IValueConverter
    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If parameter Is Nothing OrElse Not TypeOf parameter Is String OrElse String.IsNullOrEmpty(parameter) Then Return Nothing
        Dim parameters As New List(Of String)(parameter.ToString.Split(":"c))
        parameter = parameters(0)
        parameters.RemoveAt(0)
        If String.IsNullOrEmpty(parameter) Then Return value

        Dim method = (From m In GetType(String).GetMethods _
                Where m.Name = parameter _
                AndAlso m.GetParameters.Count = parameters.Count).FirstOrDefault
        If method Is Nothing Then Return value
        Return method.Invoke(value, parameters.ToArray)
    End Function
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Return value.ToString()
    End Function
End Class

C#: -converted by a tool, don't rely!

 [ValueConversion(typeof(string), typeof(object))]
public class StringConverter : IValueConverter
{
    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;
        value = value.ToString();
        if (String.IsNullOrEmpty(value as string)) return "";
        if (parameter == null || !parameter is string || String.IsNullOrEmpty((string)parameter)) return value;
        List<string> parameters = new List<string>(((string)parameter).Split(':'));
        parameter = parameters[0];
        parameters.RemoveAt(0);

        var method = (from m in typeof(String).GetMethods()
                        where m.Name== parameter 
                        && m.GetParameters().Count()==parameters.Count
                            select m).FirstOrDefault();
        if (method == null) return value;
        return method.Invoke(value, parameters.ToArray());
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value;
    }

    #endregion
}

Xaml:

<TextBox Text="{Binding Path=String, Converter={StaticResource StringConverter}, ConverterParameter=Trim:Argument:AnotherArgument}" />

Then, in the binding, when u use a converter u have an option to pass a parameter to the converter (Binding.ConverterParameter) pass all your parameters seperated with : (colon - you can change it in the String.Split delimiter parameter), while the first parameter is the function name, the function will count the extra parameters and try to pass it.
I still didn't work on the parameters addressing, it's a shallow function.

Would like to see your improvements and notes.
thanks. Shimmy

You will need to use a converter as you want to transform the data your control is bound to. To avoid writing lots of converters simple transformations, you can use the Dynamic Language Runtime and write expressions in your favourite DLR scripting language (such as Python, Ruby, etc).

See my blog series for an example of how to achieve this. Part 3 talks specifically about ValueConverters.

I created an ultimate converter for all the functions in System.String, needs some improvement would love to hear from you, hope to update it in future, please accept:

    <ValueConversion(GetType(String), GetType(String))> _
Class StringFunctions : Implements IValueConverter
    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        If parameter Is Nothing OrElse Not TypeOf parameter Is String OrElse String.IsNullOrEmpty(parameter) Then Return Nothing
        Dim parameters As New List(Of String)(parameter.ToString.Split(":"c))
        parameter = parameters(0)
        parameters.RemoveAt(0)
        If String.IsNullOrEmpty(parameter) Then Return value

        Dim method = (From m In GetType(String).GetMethods _
                Where m.Name = parameter _
                AndAlso m.GetParameters.Count = parameters.Count).FirstOrDefault
        If method Is Nothing Then Return value
        Return method.Invoke(value, parameters.ToArray)
    End Function
    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Throw New NotSupportedException
    End Function
End Class

The in the binding, when u use a converter u have an option to pass a parameter to the converter (Binding.ConverterParameter) pass all your parameters seperated with : (colon - you can change it in the String.Split delimiter parameter), while the first parameter is the function name, the function will count the extra parameters and try to pass it.
I still didn't work on the parameters addressing, it's a shallow function.

Would like to see your improvements and notes.
thanks. Shimmy

I know this post is old, but it is still the first one showing up when searching "WPF TextBox Binding Trim".

I don't have a VB answer, but please don't use a converter.
Reasons:

  1. A converter means you have to add extra XAML code to all your XAML binding everytime. Having to always add extra code is just as bad in XAML as it in is C#/VB.
  2. This will prevent you from typing a space if you have UpdateSourceTrigger=PropertyChanged set.

Use object oriented programming like it is supposed to be used. If you need a Trimmed TextBox, then create a child of TextBox called TrimmedTextBox and use that. http://www.wpfsharp.com/2014/05/15/a-simple-trimmedtextbox-for-wpf/

C#

using System.Windows.Controls;

namespace WpfSharp.UserControls
{
    public class TrimmedTextBox : TextBox
    {
        public TrimmedTextBox()
        {
            LostFocus += TrimOnLostFocus;
        }

        void TrimOnLostFocus(object sender, System.Windows.RoutedEventArgs e)
        {
            var trimTextBox = sender as TrimmedTextBox;
            if (trimTextBox != null)
                trimTextBox.Text = trimTextBox.Text.Trim();
        }
    }
}

VB (I used a converter on my C# code)

Imports System.Windows.Controls

Namespace WpfSharp.UserControls
    Public Class TrimmedTextBox
        Inherits TextBox
        Public Sub New()
            AddHandler LostFocus, AddressOf TrimOnLostFocus
        End Sub

        Private Sub TrimOnLostFocus(sender As Object, e As System.Windows.RoutedEventArgs)
            Dim trimTextBox = TryCast(sender, TrimmedTextBox)
            If trimTextBox IsNot Nothing Then
                trimTextBox.Text = trimTextBox.Text.Trim()
            End If
        End Sub
    End Class
End Namespace

Hope this helps. Please feel free to use this object as if it were public domain.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top