简体   繁体   中英

Update textbox wpf C# on string Update

I have the follow situation:

One textbox that updates when string value changes, like a log field.

my implementation:

XAML

...

       <TextBox x:Name="txtLogView" Margin="10" Grid.Row="1" TextWrapping="Wrap">
            <TextBox.Text>
                <Binding Path="TextoLog"  Mode="TwoWay" UpdateSourceTrigger="PropertyChanged"/>
            </TextBox.Text>
        </TextBox> 

...

SerialManager.cs

...
private StringBuilder logText;
...

public String TextoLog
    {
        get { return logText.ToString(); }
        set { logText.Append(value); OnPropertyChanged("TextoLog"); }

    }

...

  private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
    {

        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        TextoLog = indata;

     }

The variable logText is updated when a new data arrives on serial port, i saw that in "set" property of Textlog, put the "get" property never is called and the textbox never shows the text.

The error was resolved setting the Datacontext of textbox on mainwindow initialization, as follow:

  private void InitDataModels()
        {
            SerialManager = new SerialManager();
            cbPorts.DataContext = SerialManager;
            txtLogView.DataContext = SerialManager;

            this.DataContext = this;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM