Label doesn't display “_” character

前端 未结 7 1800
别跟我提以往
别跟我提以往 2021-01-01 09:10

My Label.Content in WPF doesn\'t display the first occurrence of \"_\" character. Why?



        
相关标签:
7条回答
  • 2021-01-01 09:30

    I have several places where text bound into a Label control has to display the '_' character. So I wrote a converter:

    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    
    namespace Converters
    {
        public class TextToLabelConverter : DependencyObject, IValueConverter
        {
            /// <inheritdoc />
            public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
            {
                return (value is string strValue)
                    ? strValue.Replace("_", "__")
                    : Binding.DoNothing;
            }
    
            /// <inheritdoc />
            public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    
    

    Use it in the XAML thusly:

    ...
        xmlns:converters="clr-namespace:Converters"
    ...
    
    <Window.Resources>
        <converters:TextToLabelConverter x:Key="TextToLabelConverter" />
    </Window.Resources>
    
    <Grid>
        <Label Content="{Binding SourceText, Converter={StaticResource TextToLabelConverter}}" />
    </Grid>
    
    
    0 讨论(0)
提交回复
热议问题