开发者

How to set the multiline property on a textbox used in WPF databinding

I am new to databinding, but got a simple program running where I bind a string of data to a textbox. This works well, everytime the string is updated it shows it in 开发者_运维百科the textbox.

However I have a need for one of my textboxes to append the data rather than to overwrite it with the new data string. 1. I know that I can append the new data string to the existing one, but would that not impact on performance in the long run, as this will cause the entire string to be bounded with the textbox every time an update is made? 2. Do you perhaps have any suggestions on how I can achieve the appending without having to worry that the entire string is copied to the textbox every time it is updated?

This string is used to output some logging information to the screen (via textbox control) and it is destined to become very large.

Hope that you can help, or give some suggestions.


There isn't a way that you can use a WPF databinding to append some data, and you are correct in your observation that each time your log string is updated the binding will re-evaluate. This could harm performance if the string gets very long. Can I suggest a different design? Instead of storing your log as a single string, why not store it as a list of discrete log messages? You can then bind this to a list in your UI. When new log items are added, it will simply add a new item within the list. This design can also take advantage of UI virtualization.

A quick code example:

ObservableCollection<string> logItems = new ObservableCollection<string>();

public ObservableCollection<string> LogItems
{
  get { return _logItems; }
}

// add items as they are logged
public AddToLog(string message)
{
  logItems.Add(message);
}

You can then bind this collection of log messages to your UI:

<ListBox x:Name="list" ItemsSource="{Binding LogItems}"/>

Or if you want to bind in code-behind ...

list.SetBinding(ListBox.ItemsSource, new Binding("LogItems")
{
  Source = this;
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜