当绑定到Wpf时,有一种使用系统的方法。不使用转换器的字符串函数?

时间:2021-01-26 16:03:45

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

当绑定到Wpf时,有一种使用系统的方法。不使用转换器的字符串函数?

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

that's basically my desire.

这基本上就是我的愿望。

5 个解决方案

#1


7  

I would use a converter.

我会用转换器。

Binding Xaml

绑定Xaml

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

StringTrimmingConverter.cs

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

如果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

#2


1  

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:

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:

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

然后,在绑定中,当您使用转换器时,您可以选择将一个参数传递给转换器(binding . converterparameter),并传递与:(冒号)分隔的所有参数。分割分隔符参数),第一个参数是函数名,函数将计数额外的参数并尝试传递它。我还没有研究参数寻址,它是一个浅函数。我想看看你的改进和笔记。谢谢。女式衬衣

#3


0  

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).

您将需要使用转换器,因为您想要转换您的控件绑定到的数据。为了避免编写大量的转换器简单转换,您可以使用动态语言运行时并使用您最喜欢的DLR脚本语言(如Python、Ruby等)编写表达式。

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

请参阅我的博客系列,了解如何实现这一点。第3部分详细介绍了valueconverter。

#4


0  

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

在绑定中,当您使用转换器u时,您可以选择将参数传递给转换器(binding . converterparameter),并传递与:(冒号)分隔的所有参数,您可以在字符串中修改它。分割分隔符参数),第一个参数是函数名,函数将计数额外的参数并尝试传递它。我还没有研究参数寻址,它是一个浅函数。我想看看你的改进和笔记。谢谢。女式衬衣

#5


0  

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

我知道这篇文章已经过时了,但它仍然是搜索“WPF文本框绑定修饰”时出现的第一个。

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

我没有VB的答案,但是请不要使用转换器。原因:

  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. 转换器意味着您必须在每次的XAML绑定中添加额外的XAML代码。必须总是添加额外的代码在XAML中和在c# /VB中一样糟糕。
  3. This will prevent you from typing a space if you have UpdateSourceTrigger=PropertyChanged set.
  4. 如果您有UpdateSourceTrigger=PropertyChanged集,这将阻止您输入空格。

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/

使用面向对象编程,就像它应该使用的那样。如果需要调整文本框,那么创建一个名为TrimmedTextBox的TextBox子文本框并使用它。http://www.wpfsharp.com/2014/05/15/a-simple-trimmedtextbox-for-wpf/

C#

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)

VB(我在c#代码中使用了一个转换器)

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.

希望这个有帮助。请随意使用这个对象,就好像它是公共领域一样。

#1


7  

I would use a converter.

我会用转换器。

Binding Xaml

绑定Xaml

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

StringTrimmingConverter.cs

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

如果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

#2


1  

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:

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:

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

然后,在绑定中,当您使用转换器时,您可以选择将一个参数传递给转换器(binding . converterparameter),并传递与:(冒号)分隔的所有参数。分割分隔符参数),第一个参数是函数名,函数将计数额外的参数并尝试传递它。我还没有研究参数寻址,它是一个浅函数。我想看看你的改进和笔记。谢谢。女式衬衣

#3


0  

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).

您将需要使用转换器,因为您想要转换您的控件绑定到的数据。为了避免编写大量的转换器简单转换,您可以使用动态语言运行时并使用您最喜欢的DLR脚本语言(如Python、Ruby等)编写表达式。

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

请参阅我的博客系列,了解如何实现这一点。第3部分详细介绍了valueconverter。

#4


0  

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

在绑定中,当您使用转换器u时,您可以选择将参数传递给转换器(binding . converterparameter),并传递与:(冒号)分隔的所有参数,您可以在字符串中修改它。分割分隔符参数),第一个参数是函数名,函数将计数额外的参数并尝试传递它。我还没有研究参数寻址,它是一个浅函数。我想看看你的改进和笔记。谢谢。女式衬衣

#5


0  

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

我知道这篇文章已经过时了,但它仍然是搜索“WPF文本框绑定修饰”时出现的第一个。

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

我没有VB的答案,但是请不要使用转换器。原因:

  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. 转换器意味着您必须在每次的XAML绑定中添加额外的XAML代码。必须总是添加额外的代码在XAML中和在c# /VB中一样糟糕。
  3. This will prevent you from typing a space if you have UpdateSourceTrigger=PropertyChanged set.
  4. 如果您有UpdateSourceTrigger=PropertyChanged集,这将阻止您输入空格。

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/

使用面向对象编程,就像它应该使用的那样。如果需要调整文本框,那么创建一个名为TrimmedTextBox的TextBox子文本框并使用它。http://www.wpfsharp.com/2014/05/15/a-simple-trimmedtextbox-for-wpf/

C#

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)

VB(我在c#代码中使用了一个转换器)

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.

希望这个有帮助。请随意使用这个对象,就好像它是公共领域一样。