189.md 13.2 KB
Newer Older
W
wizardforcel 已提交
1 2 3 4 5 6
# Mono Winforms 中的高级控件

> 原文: [http://zetcode.com/gui/csharpwinforms/advancedcontrols/](http://zetcode.com/gui/csharpwinforms/advancedcontrols/)

在 Mono Winforms 教程的这一部分中,我们介绍一些更高级的控件。 即`ListBox``ListView``TreeView`控件。

W
wizardforcel 已提交
7
## `ListBox`
W
wizardforcel 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

`ListBox`控件用于显示项目列表。 用户可以通过单击选择一个或多个项目。

`listbox.cs`

```
using System;
using System.Drawing;
using System.Windows.Forms;

class MForm : Form {

    private StatusBar sb;

    public MForm() {
        Text = "ListBox";
        Size = new Size(210, 210);

        ListBox lb = new ListBox();
        lb.Parent = this;
        lb.Items.Add("Jessica");
        lb.Items.Add("Rachel");
        lb.Items.Add("Angelina");
        lb.Items.Add("Amy");
        lb.Items.Add("Jennifer");
        lb.Items.Add("Scarlett");

        lb.Dock = DockStyle.Fill;
        lb.SelectedIndexChanged += new EventHandler(OnChanged);

        sb = new StatusBar();
        sb.Parent = this;

        CenterToScreen();
    }

    void OnChanged(object sender, EventArgs e) {
        ListBox lb = (ListBox) sender;
        sb.Text = lb.SelectedItem.ToString();
    }
}

class MApplication {
    public static void Main() {
        Application.Run(new MForm());
    }
}

```

我们的示例显示了一个具有六个名称的列表框。 所选项目显示在状态栏中。

```
ListBox lb = new ListBox();
lb.Parent = this;

```

`ListBox`控件已创建。

```
lb.Items.Add("Jessica");

```

这就是我们向`ListBox`控件添加新项目的方式。 该控件具有`Items`属性。 该属性是对列表框中项目列表的引用。 使用此参考,我们可以添加,删除或获取列表框中的项目数。

```
lb.SelectedIndexChanged += new EventHandler(OnChanged);

```

当我们选择一个项目时,会触发`SelectedIndexChanged`事件。

```
ListBox lb = (ListBox) sender;
sb.Text = lb.SelectedItem.ToString();

```

`OnChange()`方法内部,我们获得对列表框的引用,并将所选文本设置为状态栏。

![ListBox](img/14c03291822a35a66075cf47eefd22a1.jpg)

Figure: ListBox

W
wizardforcel 已提交
94
## `ListView`
W
wizardforcel 已提交
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263

`ListView`控件用于显示项目集合。 它是比`ListBox`控件更复杂的控件。 它可以在各种视图中显示数据,主要用于在多列视图中显示数据。

`listview.cs`

```
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Collections.Generic;

public class Actress
{
    public string name;
    public int year;

    public Actress(string name, int year)
    {
        this.name = name;
        this.year = year;
    }
}

class MForm : Form {

    private StatusBar sb;

    public MForm() {
        Text = "ListView";
        Size = new Size(350, 300);

        List<Actress> actresses = new List<Actress>();

        actresses.Add(new Actress("Jessica Alba", 1981));
        actresses.Add(new Actress("Angelina Jolie", 1975));
        actresses.Add(new Actress("Natalie Portman", 1981));
        actresses.Add(new Actress("Rachel Weiss", 1971));
        actresses.Add(new Actress("Scarlett Johansson", 1984));

        ColumnHeader name = new ColumnHeader();
        name.Text = "Name";
        name.Width = -1;
        ColumnHeader year = new ColumnHeader();
        year.Text = "Year";

        SuspendLayout();

        ListView lv = new ListView();
        lv.Parent = this;
        lv.FullRowSelect = true;
        lv.GridLines = true;
        lv.AllowColumnReorder = true;
        lv.Sorting = SortOrder.Ascending;
        lv.Columns.AddRange(new ColumnHeader[] {name, year});
        lv.ColumnClick += new ColumnClickEventHandler(ColumnClick);

        foreach (Actress act in actresses) {
            ListViewItem item = new ListViewItem();
            item.Text = act.name;
            item.SubItems.Add(act.year.ToString());
            lv.Items.Add(item);
        }

        lv.Dock = DockStyle.Fill;
        lv.Click += new EventHandler(OnChanged);

        sb = new StatusBar();
        sb.Parent = this;
        lv.View = View.Details;

        ResumeLayout();

        CenterToScreen();
    }

    void OnChanged(object sender, EventArgs e) {
        ListView lv = (ListView) sender;
        string name = lv.SelectedItems[0].SubItems[0].Text;
        string born = lv.SelectedItems[0].SubItems[1].Text;
        sb.Text = name + ", " + born;
    }

    void ColumnClick(object sender, ColumnClickEventArgs e)
    {
        ListView lv = (ListView) sender;

        if (lv.Sorting == SortOrder.Ascending) {
            lv.Sorting = SortOrder.Descending;
        } else {
            lv.Sorting = SortOrder.Ascending;
        }   
    }
}

class MApplication {
    public static void Main() {
        Application.Run(new MForm());
    }
}

```

在我们的示例中,我们有一个包含两列的列表视图。 在第一列中,我们显示女演员的名字。 在第二个他们的出生日期。 数据存储在`List`集合中。 通过选择一行,一行中的数据将显示在状态栏中。 另外,通过单击列标题,可以对数据进行排序。

```
public class Actress
{
...
}

```

我们使用`Actress`类存储数据。

```
List<Actress> actresses = new List<Actress>();

actresses.Add(new Actress("Jessica Alba", 1981));
actresses.Add(new Actress("Angelina Jolie", 1975));
...

```

我们创建项目并在项目中填充项目。

```
ColumnHeader name = new ColumnHeader();
name.Text = "Name";
name.Width = -1;

```

对于列表视图中的每一列,我们创建一个`ColumnHeader`。 通过将`Width`设置为-1,列的宽度等于列中最长的项目。

```
ListView lv = new ListView();
lv.Parent = this;

```

`ListView`控件已创建。

```
lv.FullRowSelect = true;
lv.GridLines = true;
lv.AllowColumnReorder = true; 
lv.Sorting = SortOrder.Ascending;

```

在这里,我们设置控件的四个属性。 该代码行支持全行选择,显示网格线,通过拖动列对列进行重新排序并以升序对数据进行排序。

```
lv.Columns.AddRange(new ColumnHeader[] {name, year});

```

在这里,我们将两个`ColumnHeader`添加到`ListView`控件中。

```
foreach (Actress act in actresses) {
    ListViewItem item = new ListViewItem();
    item.Text = act.name;
    item.SubItems.Add(act.year.ToString());
    lv.Items.Add(item);
}

```

W
wizardforcel 已提交
264
此循环填充`ListView`控件。 每行都作为`ListViewItem`类添加到列表视图。
W
wizardforcel 已提交
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297

```
lv.View = View.Details;

```

`ListView`控件可以具有不同的视图。 不同的视图以不同的方式显示数据。

```
ListView lv = (ListView) sender;
string name = lv.SelectedItems[0].SubItems[0].Text;
string born = lv.SelectedItems[0].SubItems[1].Text;
sb.Text = name + ", " + born;

```

`OnChanged()`方法内部,我们从选定的行中获取数据并将其显示在状态栏上。

```
if (lv.Sorting == SortOrder.Ascending) {
    lv.Sorting = SortOrder.Descending;
} else {
    lv.Sorting = SortOrder.Ascending;
}   

```

在这里,我们切换列的排序顺序。

![ListView](img/2f7679a2a00d6e209c20b5c46cb11634.jpg)

Figure: ListView

W
wizardforcel 已提交
298
## `TreeView`
W
wizardforcel 已提交
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531

`TreeView`控件显示项目的分层集合。 此控件中的每个项目都由`TreeNode`对象表示。

`treeview.cs`

```
using System;
using System.Drawing;
using System.Windows.Forms;

class MForm : Form {

    StatusBar sb;

    public MForm() {
        Text = "TreeView";
        Size = new Size(250, 250);

        TreeView tv = new TreeView();

        TreeNode root = new TreeNode();
        root.Text = "Languages";

        TreeNode child1 = new TreeNode();
        child1.Text = "Python";

        TreeNode child2 = new TreeNode();
        child2.Text = "Ruby";

        TreeNode child3 = new TreeNode();
        child3.Text = "Java";

        root.Nodes.AddRange(new TreeNode[] {child1, child2, child3});

        tv.Parent = this;
        tv.Nodes.Add(root);
        tv.Dock = DockStyle.Fill;
        tv.AfterSelect += new TreeViewEventHandler(AfterSelect);

        sb = new StatusBar();
        sb.Parent = this;

        CenterToScreen();
    }

    void AfterSelect(object sender, TreeViewEventArgs e)
    {
        sb.Text = e.Node.Text;
    }
}

class MApplication {
    public static void Main() {
        Application.Run(new MForm());
    }
}

```

这是`TreeView`控件的非常简单的演示。 我们有一个根项目和三个孩子。

```
TreeView tv = new TreeView();

```

我们创建`TreeView`控件。

```
TreeNode root = new TreeNode();
root.Text = "Languages";
...
tv.Nodes.Add(root);

```

在这里,我们创建一个根节点。

```
TreeNode child1 = new TreeNode();
child1.Text = "Python";

```

子节点以类似的方式创建。

```
root.Nodes.AddRange(new TreeNode[] {child1, child2, child3});

```

子节点插入到根节点的`Nodes`属性中。

![TreeView](img/ad64b7c62afa333be7cff46f1183f8fe.jpg)

Figure: TreeView

## 目录

下面的代码示例将更深入地研究`TreeView`控件。

`directories.cs`

```
using System;
using System.Drawing;
using System.Windows.Forms;
using System.IO;       

public class MForm : Form
{
  private TreeView tv;
  private Button expand;
  private Button expandAll;
  private Button collapse;
  private Button collapseAll;
  private StatusBar sb;

  private const string HOME_DIR = "/home/vronskij";

  public MForm()
  {
    Size = new Size(400, 400);
    Text = "Directories";

    tv = new TreeView();

    SuspendLayout();

    tv.Parent = this;
    tv.Location = new Point(10,10);
    tv.Size = new Size(ClientSize.Width - 20, Height - 200);
    tv.Anchor = AnchorStyles.Top | AnchorStyles.Left | 
          AnchorStyles.Right ;

    tv.FullRowSelect = false;    
    tv.ShowLines = true;      
    tv.ShowPlusMinus = true;    
    tv.Scrollable = true;      
    tv.AfterSelect += new TreeViewEventHandler(AfterSelect);

    expand = new Button();
    expand.Parent = this;
    expand.Location = new Point(20, tv.Bottom + 20);
    expand.Text = "Expand";
    expand.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    expand.Click += new EventHandler(OnExpand);

    expandAll = new Button();
    expandAll.Parent = this;
    expandAll.Location = new Point(20, expand.Bottom + 5);
    expandAll.Text = "Expand All";
    expandAll.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    expandAll.Click += new EventHandler(OnExpandAll);

    collapse = new Button();
    collapse.Parent = this;
    collapse.Location = new Point(expandAll.Right + 5, expand.Top );
    collapse.Text = "Collapse";
    collapse.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    collapse.Click += new EventHandler(OnCollapse);

    collapseAll = new Button();
    collapseAll.Parent = this;
    collapseAll.Location = new Point(collapse.Left, collapse.Bottom + 5);
    collapseAll.Text = "Collapse All";
    collapseAll.Anchor = AnchorStyles.Left | AnchorStyles.Top;
    collapseAll.Click += new EventHandler(OnCollapseAll);

    sb = new StatusBar();
    sb.Parent = this;

    ShowDirectories(tv.Nodes, HOME_DIR);

    ResumeLayout();

    CenterToScreen();
  }

  void AfterSelect(object sender, TreeViewEventArgs e)
  {
      sb.Text = e.Node.Text;
  }

  void ShowDirectories(TreeNodeCollection trvNode, string path)
  {
      DirectoryInfo dirInfo = new DirectoryInfo(path);
      if (dirInfo != null)
      {
          DirectoryInfo[] subDirs = dirInfo.GetDirectories();
          TreeNode tr = new TreeNode(dirInfo.Name);

          if (subDirs.Length > 0)
          {
              foreach (DirectoryInfo dr in subDirs)
              {   
                  if (!dr.Name.StartsWith("."))
                      ShowDirectories(tr.Nodes, dr.FullName);               
              }
          }
          trvNode.Add(tr);
      }
  }

  void OnExpand(object sender, EventArgs e)
  {
    tv.SelectedNode.Expand();
  }

  void OnExpandAll(object sender, EventArgs e)
  {
    tv.ExpandAll();
  }

  void OnCollapse(object sender, EventArgs e)
  {
    tv.SelectedNode.Collapse();
  }

  void OnCollapseAll(object sender, EventArgs e)
  {
    tv.CollapseAll();
  }

  static void Main() 
  {
    Application.Run(new MForm());
  }

}

```

W
wizardforcel 已提交
532
我们的代码示例在`TreeView`控件中显示指定主目录的目录。 该应用启动有些延迟,因为它首先读取主目录的目录结构。 表单上还有四个按钮。 这些按钮以编程方式展开和折叠节点。
W
wizardforcel 已提交
533 534 535 536 537 538

```
tv.Scrollable = true; 

```

W
wizardforcel 已提交
539
我们使`TreeView`控件可滚动,因为该控件显示了大量目录。
W
wizardforcel 已提交
540 541 542 543 544 545

```
ShowDirectories(tv.Nodes, HOME_DIR);

```

W
wizardforcel 已提交
546
`ShowDirectories()`方法使用指定主目录中可用的目录填充`TreeView`控件的节点。
W
wizardforcel 已提交
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

```
if (subDirs.Length > 0)
{
...
}

```

我们检查是否有任何子目录。

```
foreach (DirectoryInfo dr in subDirs)
{   
    if (!dr.Name.StartsWith("."))
        ShowDirectories(tr.Nodes, dr.FullName);               
}

```

我们遍历所有目录。 为此,我们使用了递归算法。 我们还跳过隐藏的目录。 它们以 Unix 系统上的点开头。

```
trvNode.Add(tr);

```

W
wizardforcel 已提交
574
此代码行实际上将目录添加到`TreeView`控件。
W
wizardforcel 已提交
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

```
void OnExpand(object sender, EventArgs e)
{
  tv.SelectedNode.Expand();
}

```

所有四个按钮都将事件插入到方法中。 这是展开按钮的方法。 它调用当前所选节点的`Expand()`方法。

![Directories](img/3c1bad73067acc9aab836a1cd739af68.jpg)

Figure: Directories

在 Mono Winforms 教程的这一部分中,我们介绍了 Winforms 库中可用的几个高级控件。