与 Wpf 绑定时,有没有办法在不使用转换器的情况下使用 System.String 函数?

发布于 2024-07-15 18:16:33 字数 156 浏览 8 评论 0原文

与 Wpf 绑定时,有没有办法在不使用转换器的情况下使用 System.String 函数?

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

这基本上就是我的愿望。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

×眷恋的温暖 2024-07-22 18:16:34

我知道这篇文章很旧,但它仍然是搜索“WPF TextBox Binding Trim”时出现的第一个文章。

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

  1. 转换器意味着您必须每次都向所有 XAML 绑定添加额外的 XAML 代码。 在 XAML 中必须始终添加额外的代码与在 C#/VB 中一样糟糕。
  2. 如果您设置了 UpdateSourceTrigger=PropertyChanged,这将阻止您键入空格。

像应该使用的那样使用面向对象编程。 如果您需要 Trimmed TextBox,则创建一个名为 TrimmedTextBox 的 TextBox 子项并使用它。 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(我在 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

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

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.

楠木可依 2024-07-22 18:16:33

我会使用转换器。

绑定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
    }
}

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

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
離人涙 2024-07-22 18:16:33

我为 System.String 中的所有函数创建了一个终极转换器,需要一些改进,希望收到您的来信,希望将来更新它,请接受:

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通过工具,不要依赖!

 [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}" />

然后,在绑定中,当您使用转换器时,您可以选择将参数传递给转换器 (Binding.ConverterParameter) pass所有参数都用 : 分隔(冒号 - 您可以在 String.Split 分隔符参数中更改它),而第一个参数是函数名称,函数将计算额外的参数并尝试传递它。
我仍然没有研究参数寻址,这是一个浅层函数。

希望看到您的改进和注释。
谢谢。
摆摆

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

简单气质女生网名 2024-07-22 18:16:33

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

有关如何实现此目的的示例,请参阅我的博客系列第 3 部分专门讨论 ValueConverters。

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.

情绪失控 2024-07-22 18:16:33

我为 System.String 中的所有函数创建了一个终极转换器,需要一些改进,希望收到您的来信,希望将来更新它,请接受:

    <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

在绑定中,当您使用转换器时,您可以选择传递转换器的参数 (Binding.ConverterParameter) 传递用 : (冒号 - 您可以在 String.Split 分隔符参数中更改它)分隔的所有参数,而第一个参数是函数名称,该函数将计算额外的参数并尝试通过它。
我仍然没有研究参数寻址,这是一个浅层函数。

希望看到您的改进和注释。
谢谢。
摆摆

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文