Domanda

Vorrei che diverse caselle di testo reagissero alle modifiche di una stringa sottostante. Quindi, se dovessi cambiare il contenuto della stringa, anche tutte quelle caselle di testo cambierebbero il loro contenuto.

Ora, non posso usare il tipo String per quello in quanto è immutabile. Quindi sono andato con StringBuilder. Ma la proprietà Text di un oggetto TextBox accetta solo String.

C'è un modo semplice per " legare " l'oggetto StringBuilder alla proprietà Text di un oggetto TextBox?

Mille grazie!

PS: TextBox è attualmente WPF. Ma potrei passare a Windows Form a causa di Mono.

È stato utile?

Soluzione

Puoi sempre esporre una proprietà che è getter restituisce ToString () del Stringbuilder. Il modulo potrebbe quindi associarsi a questa proprietà.

private StringBuilder _myStringBuilder;

public string MyText
{
  get { return _myStringBuilder.ToString(); }
}

Altri suggerimenti

Sembra che la mia risposta precedente non sia stata formulata molto bene, poiché molte persone hanno frainteso il punto che stavo sollevando, quindi proverò di nuovo a tenere conto dei commenti delle persone.

Solo perché un oggetto String è immutabile non significa che una variabile di tipo String non può essere modificata. Se un oggetto ha una proprietà di tipo String, l'assegnazione di un nuovo oggetto String a quella proprietà provoca la modifica della proprietà (nella mia risposta originale, mi riferivo a questa come mutazione variabile, a quanto pare alcune persone non sono d'accordo con l'uso del termine " ; muta " in questo contesto).

Il sistema di banca dati WPF può essere associato a questa proprietà. Se viene notificato che la proprietà cambia tramite INotifyPropertyChanged, aggiornerà la destinazione dell'associazione, consentendo così a molte caselle di testo di associarsi alla stessa proprietà e tutte le modifiche su un aggiornamento della proprietà senza richiedere alcun codice aggiuntivo.

Pertanto, non è necessario utilizzare StringBuilder come archivio di supporto per la proprietà. Invece, puoi usare una proprietà String standard e implementare INotifyPropertyChanged.

public class MyClass : INotifyPropertyChanged
{
    private string myString;

    public string MyString
    {
        get
        { return myString; }
        set
        {
            myString = value;
            OnPropertyChanged("MyString");
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
        { handler(this, new PropertyChangedEventArgs(propertyName)); }
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

WPF può associarsi a questo e prenderà automaticamente e le modifiche apportate al valore della proprietà . No, l'oggetto String non è stato modificato, ma la proprietà String è modificata (o modificata, se si preferisce).

Ecco cosa uso per associare StringBuilder a TextBox in WPF:

public class BindableStringBuilder : INotifyPropertyChanged
{
    private readonly StringBuilder _builder = new StringBuilder();

    private EventHandler<EventArgs> TextChanged;

    public string Text
    {
        get { return _builder.ToString(); }
    }

    public int Count
    {
        get { return _builder.Length; }
    }

    public void Append(string text)
    {
        _builder.Append(text);
        if (TextChanged != null)
            TextChanged(this, null);
        RaisePropertyChanged(() => Text);
    }

    public void AppendLine(string text)
    {
        _builder.AppendLine(text);
        if (TextChanged != null)
            TextChanged(this, null);
        RaisePropertyChanged(() => Text);
    }

    public void Clear()
    {
        _builder.Clear();
        if (TextChanged != null)
            TextChanged(this, null);
        RaisePropertyChanged(() => Text);
    }

    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string property)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(property));
        }
    }

    public void RaisePropertyChanged<T>(Expression<Func<T>> propertyExpression)
    {
        if (propertyExpression == null)
        {
            return;
        }

        var handler = PropertyChanged;

        if (handler != null)
        {
            var body = propertyExpression.Body as MemberExpression;
            if (body != null)
                handler(this, new PropertyChangedEventArgs(body.Member.Name));
        }
    }

    #endregion


}

In ViewModel:

public BindableStringBuilder ErrorMessages { get; set; }
ErrorMessages.AppendLine("Missing Image: " + imagePath);

In Xaml:

<TextBox Text="{Binding ErrorMessages.Text, Mode=OneWay}"/>

Ovviamente puoi esporre altri metodi StringBuilder se necessario.

È possibile ereditare la casella di testo e sovrascrivere la proprietà Text per recuperare e scrivere nel generatore di stringhe.

In poche parole, no. La proprietà Text accetta solo una stringa. Quindi, qualunque sia la fonte, dovrai convertirla in una stringa.

Per consentirti di impostarlo facilmente una volta per molte caselle di testo, puoi avere una proprietà di classe che imposta sempre tutti i valori delle caselle di testo ...

public string MyString
{
  get
  {
   ///... 
  }
  set 
  {
    textbox1.Text = value;
    textbox2.Text = value;
    //...
  }
}

Vorrei racchiudere StringBuilder in una classe personalizzata con un metodo Aggiungi , un metodo Text e un OnChanged evento.

Collega il metodo Aggiungi in modo tale che quando viene chiamato aggiunge il testo all'istanza StringBuilder e genera l'evento. Quindi quando l'evento si attiva, usa il metodo Text per eseguire un ToString su StringBuilder .

public class StringBuilderWrapper
{
   private StringBuilder _builder = new StringBuilder();
   private EventHandler<EventArgs> TextChanged;
   public void Add(string text)
   {
     _builder.Append(text);
     if (TextChanged != null)
       TextChanged(this, null);
   }
   public string Text
   {
     get { return _builder.ToString(); }
   }
}

Puoi associare la proprietà Text di una TextBox a una proprietà stringa ... L'oggetto String è immutabile, ma una variabile di tipo String è perfettamente mutabile ...

string mutable = "I can be changed";
mutable = "see?";

Dovresti avvolgerlo in un oggetto che implementa INotifyPropertyChanged, tuttavia.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top