簡體   English   中英

如何將TextBox.Lines綁定到BindingList <string> 在C#中的WinForms中?

[英]How to bind TextBox.Lines to BindingList<string> in WinForms in C#?

我有

private BindingList<string> log;

我的表單上有多行logTextBox。 如何將“日志”列表綁定到該文本框?

我不需要2路綁定。 從日志綁定到texbox的一種方法就足夠了。

不能直接從結合BindingList<string>TextBox ,因為Lines在屬性TextBox的類型的string[]BindingList<string>

您需要一個string[]屬性,並將屬性更改通知更改為相同。

這是您如何執行此操作的示例。

public class LinesDataSource : INotifyPropertyChanged
{
    private BindingList<string> lines = new BindingList<string>();

    public LinesDataSource()
    {
        lines.ListChanged += (sender, e) => OnPropertyChanged("LinesArray");
    }

    public BindingList<string> Lines
    {
        get { return lines; }
    }

    public string[] LinesArray
    {
        get
        {
            return lines.ToArray();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

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

然后在表單/用戶控件中

private LinesDataSource dataSource = new LinesDataSource();

private void Setup()
{
    textBox.DataBindings.Add("Lines", dataSource, "LinesArray");
    Populate();
}

private void Populate()
{
    dataSource.Lines.Add("whatever");
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM