Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Учебник_ПОА.doc
Скачиваний:
93
Добавлен:
13.02.2015
Размер:
2.65 Mб
Скачать

Common wpf Controls

Windows Presentation Foundation (WPF) enables you to create visually enhanced user interfaces for your applications. Even the typical controls you're used to seeing in a standard Windows Forms application are enhanced in WPF applications. The standard WPF controls resemble those you'll find in the Toolbox for Windows Forms. WPF controls are part of the System.Windows.Controls namespace instead of the System.Windows.Forms namespace. WPF controls can also be created by using XAML markup.

When you drag WPF controls from the Toolbox to the design surface, the controls resemble controls in a Windows Form application. However, WPF controls can be customized. Controls in WPF support styles and templates that enable you to create visually compelling applications. To modify the appearance of a control, you add styles and attributes to the control in the XAML editor. Because writing XAML markup manually is difficult, you might want to consider using an application than can generate XAML for you, such as Expression Blend.

Procedure To add a control to the wpf window

  1. On the File menu, click New Project.

  2. In the New Project dialog box, in the Templates pane, click WPF Application.

  3. In the Name box, type WPFControls, and then click OK.

  4. A new Windows Presentation Foundation project is created.

  5. From the Toolbox, drag a TextBox control to the upper-right side of the WPF window.

  6. Click the text box.

Стандартные элементы управления wpf

Windows Presentation Foundation (WPF) позволяет создавать визуально усовершенствованные пользовательские интерфейсы для приложений. В приложениях WPF улучшены даже стандартные элементы управления приложений Windows Forms. Стандартные элементы WPF похожи на те, что находятся на панели элементов для Windows Forms. Элементы управления WPF являются частью пространства имен System.Windows.Controls, а не пространства имен System.Windows.Forms. Также элементы управления WPF можно создавать с помощью разметки XAML.

При перетаскивании элементов управления WPF из панели элементов на поверхность разработки они похожи на элементы управления в приложении Windows Forms. Однако элементы управления WPF могут быть настроены. Элементы управления в WPF поддерживают стили и шаблоны, позволяющие создавать визуально привлекательные приложения. Для изменения внешнего вида элемента управления добавьте к нему стили и атрибуты в редакторе XAML. Поскольку самостоятельное написание разметки XAML является трудной задачей, попробуйте использовать для формирования XAML приложение, такое как Expression Blend.

Процедура Добавление элемента управления в окно wpf

  1. В меню Файл выберите команду Создать проект.

  2. В диалоговом окне Создание проекта в области Шаблоны выберите Приложение WPF.

  3. В окне Имя введите WPFControls и нажмите кнопку ОК.

  4. Будет создан новый проект Windows Presentation Foundation.

  5. Перетащите элемент управления TextBox с панели элементов в верхнюю правую часть окна WPF.

  6. Щелкните текстовое поле.

  7. Set the following properties for the text box in the Properties window.

    Property

    Value

    VerticalAlignment

    Top

    Width

    75

    Height

    26

  8. Add a Button control to the WPF window, next to the text box.

  9. Change the text between the opening and closing Button tags in the XAML Editor from Button to Add, as shown in the following example.

    <Button Height="23" HorizontalAlignment="Right" Margin="0,59,35,0"

    Name="Button1" VerticalAlignment="Top"

    Width="75">Add</Button>

  10. The text on the button changes after you type the new value.

  11. Add a ListBox control to the WPF window underneath the text box.

  12. Double-click the button to add the default event handler, and add the following code:

    if (textBox1.Text != "")

    {

    listBox1.Items.Add(textBox1.Text);

    textBox1.Text = "";

    }

  13. Press F5 to run your program. A window that contains the text box, list box, and button that you just added appears.

  14. Type some text in the text box and then click the Add button. Verify that the text was added to the list box.

  15. Add additional text to the list box.

  1. Задайте следующие свойства для текстового поля в окне Свойства.

    Свойство

    Значение

    VerticalAlignment

    Верхний край

    Ширина

    75

    Высота

    26

  2. Добавьте в окно WPF элемент управления Button рядом с текстовым полем.

  3. Измените текст между открывающим и закрывающим тегами Button в редакторе XAML с Button на Add, как показано в следующем примере.

    <Button Height="23" HorizontalAlignment="Right" Margin="0,59,35,0"

    Name="Button1" VerticalAlignment="Top"

    Width="75">Add</Button>

  4. После ввода нового значения текст на кнопке изменится.

  5. Добавьте элемент управления ListBox в окно WPF под текстовым полем.

  6. Дважды щелкните кнопку для добавления обработчика событий по умолчанию, и вставьте следующий код:

    if (textBox1.Text != "")

    {

    listBox1.Items.Add(textBox1.Text);

    textBox1.Text = "";

    }

  7. Нажмите клавишу F5 для выполнения программы. Откроется окно, содержащее добавленные текстовое поле, список и кнопку.

  8. Введите какой-нибудь текст в текстовом поле и нажмите кнопку "Добавить". Убедитесь, что текст добавился в список.

  9. Добавьте дополнительный текст в список.