달력

2

« 2025/2 »

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
2016. 11. 5. 14:31

Controls 프로그래밍/WPF2016. 11. 5. 14:31

Controls



https://msdn.microsoft.com/ko-KR/library/bb613551(v=vs.110).aspx

https://msdn.microsoft.com/en-US/library/bb613551(v=vs.110).aspx




Windows Presentation Foundation (WPF) ships with many of the common UI components that are used in almost every Windows application, such asButtonLabelTextBoxMenu, and ListBox. Historically, these objects have been referred to as controls. While the WPF SDK continues to use the term "control" to loosely mean any class that represents a visible object in an application, it is important to note that a class does not need to inherit from the Control class to have a visible presence. Classes that inherit from the Control class contain a ControlTemplate, which allows the consumer of a control to radically change the control's appearance without having to create a new subclass. This topic discusses how controls (both those that do inherit from the Control class and those that do not) are commonly used in WPF.

Creating an Instance of a Control

You can add a control to an application by using either Extensible Application Markup Language (XAML) or code. The following example shows how to create a simple application that asks a user for their first and last name. This example creates six controls: two labels, two text boxes, and two buttons, in XAML. All controls can be created similarly.

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="30"/>
    <RowDefinition Height="30"/>
    <RowDefinition Height="30"/>
    <RowDefinition/>
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition/>
    <ColumnDefinition/>
  </Grid.ColumnDefinitions>

  <Label>
    Enter your first name:
  </Label>
  <TextBox Grid.Row="0" Grid.Column="1" 
           Name="firstName" Margin="0,5,10,5"/>

  <Label Grid.Row="1" >
    Enter your last name:
  </Label>
  <TextBox Grid.Row="1" Grid.Column="1" 
           Name="lastName" Margin="0,5,10,5"/>

  <Button Grid.Row="2" Grid.Column="0" 
          Name="submit" Margin="2">
    View message
  </Button>

  <Button Grid.Row="2" Grid.Column="1" 
          Name="Clear" Margin="2">
    Clear Name
  </Button>
</Grid>

The following example creates the same application in code. For brevity, the creation of the Gridgrid1, has been excluded from the sample. grid1has the same column and row definitions as shown in the preceding XAML example.

Label firstNameLabel;
Label lastNameLabel;
TextBox firstName;
TextBox lastName;
Button submit;
Button clear;

void CreateControls()
{
    firstNameLabel = new Label();
    firstNameLabel.Content = "Enter your first name:";
    grid1.Children.Add(firstNameLabel);

    firstName = new TextBox();
    firstName.Margin = new Thickness(0, 5, 10, 5);
    Grid.SetColumn(firstName, 1);
    grid1.Children.Add(firstName);

    lastNameLabel = new Label();
    lastNameLabel.Content = "Enter your last name:";
    Grid.SetRow(lastNameLabel, 1);
    grid1.Children.Add(lastNameLabel);

    lastName = new TextBox();
    lastName.Margin = new Thickness(0, 5, 10, 5);
    Grid.SetColumn(lastName, 1);
    Grid.SetRow(lastName, 1);
    grid1.Children.Add(lastName);

    submit = new Button();
    submit.Content = "View message";
    Grid.SetRow(submit, 2);
    grid1.Children.Add(submit);

    clear = new Button();
    clear.Content = "Clear Name";
    Grid.SetRow(clear, 2);
    Grid.SetColumn(clear, 1);
    grid1.Children.Add(clear);

}

Changing the Appearance of a Control

It is common to change the appearance of a control to fit the look and feel of your application. You can change the appearance of a control by doing one of the following, depending on what you want to accomplish:

  • Change the value of a property of the control.

  • Create a Style for the control.

  • Create a new ControlTemplate for the control.

Changing a Control's Property Value

Many controls have properties that allow you to change how the control appears, such as the Background of a Button. You can set the value properties in both XAML and code. The following example sets the BackgroundFontSize, and FontWeight properties on a Button in XAML.

<Button FontSize="14" FontWeight="Bold">
  <!--Set the Background property of the Button to
    a LinearGradientBrush.-->
  <Button.Background>
    <LinearGradientBrush StartPoint="0,0.5" 
                            EndPoint="1,0.5">
      <GradientStop Color="Green" Offset="0.0" />
      <GradientStop Color="White" Offset="0.9" />
    </LinearGradientBrush>

  </Button.Background>
  View message
</Button>

The following example sets the same properties in code.

LinearGradientBrush buttonBrush = new LinearGradientBrush();
buttonBrush.StartPoint = new Point(0, 0.5);
buttonBrush.EndPoint = new Point(1, 0.5);
buttonBrush.GradientStops.Add(new GradientStop(Colors.Green, 0));
buttonBrush.GradientStops.Add(new GradientStop(Colors.White, 0.9));

submit.Background = buttonBrush;
submit.FontSize = 14;
submit.FontWeight = FontWeights.Bold;

Creating a Style for a Control

WPF gives you the ability to specify the appearance of controls wholesale, instead of setting properties on each instance in the application, by creating a Style. The following example creates a Style that is applied to each Button in the application.  Style definitions are typically defined in XAML in a ResourceDictionary, such as the Resources property of the FrameworkElement.

<Style TargetType="Button">
  <Setter Property="FontSize" Value="14"/>
  <Setter Property="FontWeight" Value="Bold"/>
  <Setter Property="Background">
    <Setter.Value>
      <LinearGradientBrush StartPoint="0,0.5" 
                              EndPoint="1,0.5">
        <GradientStop Color="Green" Offset="0.0" />
        <GradientStop Color="White" Offset="0.9" />
      </LinearGradientBrush>

    </Setter.Value>
  </Setter>
</Style>

You can also apply a style to only certain controls of a specific type by assigning a key to the style and specifying that key in the Style property of your control. For more information about styles, see Styling and Templating.

Creating a ControlTemplate

Style allows you to set properties on multiple controls at a time, but sometimes you might want to customize the appearance of a Controlbeyond what you can do by creating a Style. Classes that inherit from the Control class have a ControlTemplate, which defines the structure and appearance of a Control. The Template property of a Control is public, so you can give a Control a ControlTemplate that is different than its default. You can often specify a new ControlTemplate for a Control instead of inheriting from a control to customize the appearance of a Control.

Consider the very common control, Button. The primary behavior of a Button is to enable an application to take some action when the user clicks it. By default, the Button in WPF appears as a raised rectangle. While developing an application, you might want to take advantage of the behavior of a Button--that is, by handling the button's click event--but you might change the button's appearance beyond what you can do by changing the button's properties. In this case, you can create a new ControlTemplate.

The following example creates a ControlTemplate for a Button. The ControlTemplate creates a Button with rounded corners and a gradient background. The ControlTemplate contains a Border whose Background is a LinearGradientBrush with two GradientStop objects. The firstGradientStop uses data binding to bind the Color property of the GradientStop to the color of the button's background. When you set theBackground property of the Button, the color of that value will be used as the first GradientStop. For more information about data binding, seeData Binding Overview. The example also creates a Trigger that changes the appearance of the Button when IsPressed is true.

<!--Define a template that creates a gradient-colored button.-->
<Style TargetType="Button">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="Button">
        <Border 
          x:Name="Border"  
          CornerRadius="20" 
          BorderThickness="1"
          BorderBrush="Black">
          <Border.Background>
            <LinearGradientBrush StartPoint="0,0.5" 
                                 EndPoint="1,0.5">
              <GradientStop Color="{Binding Background.Color, 
                    RelativeSource={RelativeSource TemplatedParent}}" 
                            Offset="0.0" />
              <GradientStop Color="White" Offset="0.9" />
            </LinearGradientBrush>
          </Border.Background>
          <ContentPresenter 
            Margin="2"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            RecognizesAccessKey="True"/>
        </Border>
        <ControlTemplate.Triggers>
          <!--Change the appearance of
          the button when the user clicks it.-->
          <Trigger Property="IsPressed" Value="true">
            <Setter TargetName="Border" Property="Background">
              <Setter.Value>
                <LinearGradientBrush StartPoint="0,0.5" 
                                     EndPoint="1,0.5">
                  <GradientStop Color="{Binding Background.Color, 
                    RelativeSource={RelativeSource TemplatedParent}}" 
                                Offset="0.0" />
                  <GradientStop Color="DarkSlateGray" Offset="0.9" />
                </LinearGradientBrush>
              </Setter.Value>
            </Setter>
          </Trigger>

        </ControlTemplate.Triggers>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>
<Button Grid.Row="2" Grid.ColumnSpan="2" Name="submitName"
        Background="Green">View message</Button>
System_CAPS_noteNote

The Background property of the Button must be set to a SolidColorBrush for the example to work properly.

Subscribing to Events

You can subscribe to a control's event by using either XAML or code, but you can only handle an event in code. The following example shows how to subscribe to the Click event of a Button.

<Button Grid.Row="2" Grid.ColumnSpan="2" Name="submitName" Click="submit_Click"
  Background="Green">View message</Button>
submit.Click += new RoutedEventHandler(submit_Click);

The following example handles the Click event of a Button.

void submit_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Hello, " + firstName.Text + " " + lastName.Text);
}

Rich Content in Controls

Most classes that inherit from the Control class have the capacity to contain rich content. For example, a Label can contain any object, such as a string, an Image, or a Panel. The following classes provide support for rich content and act as base classes for most of the controls in WPF.

For more information about these base classes, see WPF Content Model.





Controls by Category


Windows Presentation Foundation (WPF) controls can be logically grouped into several categories. These categories can be used to select the appropriate control for your scenario by helping you see which controls have similar usage patterns or functionality.

Buttons

Buttons are one of the most basic user interface controls. Applications typically perform some task in the Click event when a user clicks on them.

Data Display

Data display controls are used to show information from a data source.

Date Display and Selection

Date controls are used to display and select calendar information.

Menus

Menus are used to group related actions or to provide contextual assistance.

Selection

Selection controls are used to enable a user to select one or more options.

Navigation

Navigation controls enhance or extend the application navigation experience by creating targeting frames or tabbed application appearance.

Dialog Boxes

Dialog boxes provide targeted support for common user-interaction scenarios such as printing.

User Information

User information controls provide contextual feedback or clarify an application's user interface. The user typically cannot interact with these controls.

Documents

WPF includes several specialized controls for viewing documents. These controls optimize the reading experience, based on the targeted user scenario.

Input

Input controls enable the user to input text and other content.

Media

WPF includes integrated support for hosting both audio and video content, as well as codecs for most popular image formats.

Digital Ink

Digital ink controls provide integrated support for Tablet PC features, such as ink viewing and ink input.





WPF Content Model


Windows Presentation Foundation (WPF) is a presentation platform that provides many controls and control-like types whose primary purpose is to display different types of content. To determine which control to use or which control to derive from, you should understand the kinds of objects a particular control can best display.

This topic summarizes the content model for WPF control and control-like types. The content model describes what content can be used in a control. This topic also lists the content properties for each content model. A content property is a property that is used to store the content of the object.

Classes That Contain Arbitrary Content

Some controls can contain an object of any type, such as a string, a DateTime object, or a UIElement that is a container for additional items. For example, a Button can contain an image and some text; or a CheckBox can contain the value of DateTime.Now.

WPF has four classes that can contain arbitrary content. The following table lists the classes, which inherit from Control.

Class that contains arbitrary content

Content

ContentControl

A single arbitrary object.

HeaderedContentControl

A header and a single item, both of which are arbitrary objects.

ItemsControl

A collection of arbitrary objects.

HeaderedItemsControl

A header and a collection of items, all of which are arbitrary objects.

Controls that inherit from these classes can contain the same type of content and treat the content in the same way. The following illustration shows one control from each content model that contains an image and some text.

Button, GroupBox, Listbax, TreeViewItem

Controls That Contain a Single Arbitrary Object

The ContentControl class contains a single piece of arbitrary content. Its content property is Content. The following controls inherit from ContentControl and use its content model:

The following illustration shows four buttons whose Content is set to a string, a DateTime object, a Rectangle, and a Panel that contains an Ellipseand a TextBlock.

Four buttons

Four buttons that have different types of content

For an example of how to set the Content property, see ContentControl.

Controls That Contain a Header and a Single Arbitrary Object

The HeaderedContentControl class inherits from ContentControl and displays content with a header. It inherits the content property, Content, from ContentControl and defines the Header property that is of type Object; therefore, both can be an arbitrary object.

The following controls inherit from HeaderedContentControl and use its content model:

The following illustration shows two TabItem objects. The first TabItem has UIElement objects as the Header and the Content. The Header is set to a StackPanel that contains an Ellipse and a TextBlock. The Content is set to a StackPanel that contains a TextBlock and a Label. The second TabItemhas a string in the Header and a TextBlock in the Content.

TabControl

TabControl that uses different types in the Header property

For an example of how to create TabItem objects, see HeaderedContentControl.

Controls That Contain a Collection of Arbitrary Objects

The ItemsControl class inherits from Control and can contain multiple items, such as strings, objects, or other elements. Its content properties are ItemsSource and ItemsItemsSource is typically used to populate the ItemsControl with a data collection. If you do not want to use a collection to populate the ItemsControl, you can add items by using the Items property.

The following controls inherit from ItemsControl and use its content model:

The following illustration shows a ListBox that contains these types of items:

ListBox with four types of content

ListBox that contains multiple types of objects

Controls That Contain a Header and a Collection of Arbitrary Objects

The HeaderedItemsControl class inherits from ItemsControl and can contain multiple items, such as strings, objects, or other elements, and a header. It inherits the ItemsControl content properties, ItemsSource, and Items, and it defines the Header property that can be an arbitrary object.

The following controls inherit from HeaderedItemsControl and use its content model:

Classes That Contain a Collection of UIElement Objects

The Panel class positions and arranges child UIElement objects. Its content property is Children.

The following classes inherit from the Panel class and use its content model:

For more information, see Panels Overview.

Classes That Affect the Appearance of a UIElement

The Decorator class applies visual effects onto or around a single child UIElement. Its content property is Child. The following classes inherit from Decorator and use its content model:

The following illustration shows a TextBox that has (is decorated with) a Border around it.

TextBox with black border

TextBlock that has a Border

Classes That Provide Visual Feedback About a UIElement

The Adorner class provides visual cues to a user. For example, use an Adorner to add functional handles to elements or provide state information about a control. The Adorner class provides a framework so that you can create your own adorners. WPF does not provide any implemented adorners. For more information, see Adorners Overview.

Classes That Enable Users to Enter Text

WPF provides three primary controls that enable users to enter text. Each control displays the text differently. The following table lists these three text-related controls, their capabilities when they display text, and their properties that contain the control's text.

Control

Text is displayed as

Content property

TextBox

Plain text

Text

RichTextBox

Formatted text

Document

PasswordBox

Hidden text (characters are masked)

Password

Classes That Display Your Text

Several classes can be used to display plain or formatted text. You can use TextBlock to display small amounts of text. If you want to display large amounts of text, use the FlowDocumentReaderFlowDocumentPageViewer, or FlowDocumentScrollViewer controls.

The TextBlock has two content properties: Text and Inlines. When you want to display text that uses consistent formatting, the Text property is often your best choice. If you plan to use different formatting throughout the text, use the Inlines property. The Inlines property is a collection of Inlineobjects, which specify how to format text.

The following table lists the content property for FlowDocumentReaderFlowDocumentPageViewer, and FlowDocumentScrollViewer classes.

The FlowDocument implements the IDocumentPaginatorSource interface; therefore, all three classes can take a FlowDocument as content.

TextElement and its related classes allow you to format text. TextElement objects contain and format text in TextBlock and FlowDocument objects. The two primary types of TextElement objects are Block elements and Inline elements. A Block element represents a block of text, such as a paragraph or list. An Inline element represents a portion of text in a block. Many Inline classes specify formatting for the text to which they are applied. Each TextElement has its own content model. For more information, see the TextElement Content Model Overview.










'프로그래밍 > WPF' 카테고리의 다른 글

Control Library 3  (0) 2016.11.18
Control Library 2  (0) 2016.11.13
WPF Unmanaged API Reference  (0) 2016.11.05
Threading Model  (0) 2016.11.05
Performance  (0) 2016.11.05
:
Posted by 지훈2