Текстовое поле, возвращающее странную строку, когда пробел является последним символом - PullRequest
0 голосов
/ 21 декабря 2011

Я пытаюсь прочитать вставку символов в текстовое поле, однако я нахожу это трудным, потому что если мой последний символ - это пробел (строка должна читаться «как есть», это требование), свойство Textbox Textвозвращает что-то вроде "\ r \ n" (да, с примерно 8 пробелами).

Есть предложения о том, как этого избежать?Мне нужно прочитать этот последний пробел, а не удалять его, но я не хочу, чтобы эта странная вещь.

Спасибо за любой ответ.

Редактировать 1:

xaml

<Window x:Class="GSdk.SkypePlugin.ConfigureWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="GSdk.SkypePlugin configuration" Height="308" Width="486" WindowStartupLocation="CenterScreen" WindowStyle="ToolWindow" Topmost="True">
    <Grid>
        <TextBlock Height="60" HorizontalAlignment="Left" Margin="39,54,0,0" Name="textBlock1" Text="How much time should be displayed the plugin as a foreground applet for each word (seconds):" VerticalAlignment="Top" Width="375" TextWrapping="Wrap" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="textBlock2" Text="Should the applet be displayed over everything when a message is received:" VerticalAlignment="Top" />
        <TextBlock Height="23" HorizontalAlignment="Left" Margin="12,32,0,0" Name="textBlock3" Text="(care with this option, if SkypePlugin has focus, it will lose it)" VerticalAlignment="Top" />
        <CheckBox Height="16" HorizontalAlignment="Left" Margin="401,32,0,0" Name="showWhenMessageIncomingCheckbox" VerticalAlignment="Top" />
        <Slider Height="23" HorizontalAlignment="Left" Margin="39,91,0,0" Name="SecondsPerWordSlider" VerticalAlignment="Top" Width="375" Minimum="1" Value="1" AutoToolTipPlacement="BottomRight" AutoToolTipPrecision="1" LargeChange="0.1" SmallChange="0.01" />
        <Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="389,246,0,0" Name="saveButton" VerticalAlignment="Top" Width="75" Click="saveButton_Click" />
        <Button Content="Cancel" Height="23" HorizontalAlignment="Left" Margin="305,246,0,0" Name="cancelButton" VerticalAlignment="Top" Width="75" Click="cancelButton_Click" />
        <Label Height="28" HorizontalAlignment="Left" Margin="420,86,0,0" Name="label1" VerticalAlignment="Top" Width="32" Content="{Binding ElementName=SecondsPerWordSlider, Path=Value}" />
        <TextBox xml:space="preserve" Height="23" HorizontalAlignment="Right" Margin="0,129,170,0" Name="m_MessageSeparatorTextbox" VerticalAlignment="Top" Width="120" IsEnabled="{Binding ElementName=m_UseMessageSeparator, Path=IsChecked}" Text=" " />
        <CheckBox Content="Use message separator:" Height="16" HorizontalAlignment="Left" Margin="12,132,0,0" Name="m_UseMessageSeparator" VerticalAlignment="Top" />
    </Grid>
</Window>

cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Drawing;
using System.Windows.Interop;

namespace GSdk.SkypePlugin
{
    /// <summary>
    /// Logica di interazione per ConfigureWindowxaml.xaml
    /// </summary>
    public partial class ConfigureWindow : Window
    {
        public ConfigureWindow(double secondsPerWord = 1.0, bool showWhenMessageIncoming = true, bool useMessageSeparator = true, string messageSeparator = " ")
        {
            InitializeComponent();

            Icon = Imaging.CreateBitmapSourceFromHBitmap(Properties.Resources.LCDMedia_SkypePluginAppIcon.ToBitmap().GetHbitmap(), IntPtr.Zero, Int32Rect.Empty,                    BitmapSizeOptions.FromEmptyOptions());
            SecondsPerWordSlider.Value = secondsPerWord;
            showWhenMessageIncomingCheckbox.IsChecked = showWhenMessageIncoming;
            m_UseMessageSeparator.IsChecked = useMessageSeparator;
            m_MessageSeparatorTextbox.Text = messageSeparator;
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
        }

        public bool ShowWhenMessageIncoming { get { return (showWhenMessageIncomingCheckbox.IsChecked.HasValue ? showWhenMessageIncomingCheckbox.IsChecked.Value : false); } }
        public double SecondsPerWord { get { return SecondsPerWordSlider.Value; } }
        public string MessageSeparator { get { return m_MessageSeparatorTextbox.IsEnabled ? m_MessageSeparatorTextbox.Text : " "; } }
        public bool UseMessageSeparator { get { return m_UseMessageSeparator.IsChecked.HasValue ? m_UseMessageSeparator.IsChecked.Value : true; } }
    }
}

телефонный код

    private void AppletConfigureHandler(object sender, EventArgs e)
    {
        App.Current.Dispatcher.BeginInvoke(new Action<SkypeApplet>(a =>
        {
            bool restart = false;
            lock (a.SyncRoot)
            {
                var w = new ConfigureWindow(Properties.Settings.Default.SecondsPerWord, Properties.Settings.Default.ShowWhenMessageIncoming, Properties.Settings.Default.UseMessageSeparator, Properties.Settings.Default.MessageSeparator);
                var result = w.ShowDialog();
                if (result.HasValue && result.Value == true)
                {
                    Properties.Settings.Default.SecondsPerWord = w.SecondsPerWord;
                    Properties.Settings.Default.ShowWhenMessageIncoming = w.ShowWhenMessageIncoming;
                    Properties.Settings.Default.MessageSeparator = w.MessageSeparator;
                    Properties.Settings.Default.UseMessageSeparator = w.UseMessageSeparator;
                    Properties.Settings.Default.Save();
                    restart = true;
                }
            }
            if (restart)
                App.Restart();
        }), this);
    }

Примечание: В данный момент я тестировал xml: space, обычно его там нет.

1 Ответ

0 голосов
/ 21 декабря 2011

Извините за это, похоже, что я нашел проблему самостоятельно и очень глупо.

Infact, я почему-то сохранил "\ r \ n" в строке настроек.После перезагрузки в моем окне конфигурации кажется, что я не смог удалить эту строку из моего текста в текстовом поле, потому что мое текстовое поле состоит из одной строки, в то время как \ r \ n находится во второй строке.

I 'Я до сих пор не уверен, почему я не могу удалить все эти пробелы, но я думаю, что это ответ.Если у кого-то есть лучшее, я буду рад ему / ей.

Спасибо.

Редактировать 1: Кажется, что-то напортачило между app.config иФайл .settings, я исправил его, отредактировав их оба вручную.

Редактировать 2: Я обнаружил проблему: если я перезагружаю приложение сразу после сохранения, я не знаю, почему мойстрока заполняется этими символами.Я не понимаю, почему это происходит.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...