Megosztás a következőn keresztül:


Mik azok a vezérlők?

A Windows Presentation Foundation (WPF) számos gyakori felhasználói felületi összetevőt tartalmaz, amelyeket szinte minden Windows-alkalmazásban használnak, például Button, Label, TextBoxMenués ListBox. Ezeket az objektumokat korábban vezérlőknek nevezzük. A "control" kifejezés lazán azt jelenti, hogy minden olyan osztály, amely egy alkalmazásban látható objektumot jelöl. Fontos megjegyezni, hogy egy osztálynak nem kell a Control osztálytól örökölnie ahhoz, hogy látható jelenléttel rendelkezzen. Az osztálytól Control öröklő osztályok tartalmaznak egy olyan osztályt ControlTemplate, amely lehetővé teszi, hogy egy vezérlő felhasználója gyökeresen megváltoztassa a vezérlő megjelenését anélkül, hogy új alosztályt kellene létrehoznia. Ez a cikk bemutatja, hogyan használják a vezérlőket a WPF-ben, legyenek azok a Control osztályból öröklődőek vagy nem öröklődőek.

Vezérlőpéldány létrehozása

Egy vezérlőt egy alkalmazáshoz XAML használatával vagy kóddal adhat hozzá. Vegyük például egy WPF-ablak következő képét, amely a felhasználó nevét és címét kéri:

Képernyőkép egy WPF-alkalmazásról két, névvel és címmel ellátott szövegmezővel. Két gomb látható. Az egyik gomb neve

Ebben az ablakban hat vezérlő található: két címke, két szövegdoboz és két gomb. Az XAML a következő kódrészletben látható módon hozza létre ezeket a vezérlőket:

<Window x:Class="Examples.ExampleApp"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Input Record" Height="Auto" Width="300" SizeToContent="Height">
    <Grid Margin="5">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <Label>Enter your name:</Label>
        <TextBox Grid.Row="0" Grid.Column="1" Name="FirstName" Margin="2" />

        <Label Grid.Row="1">Enter your address:</Label>
        <TextBox Grid.Row="1" Grid.Column="1" Name="LastName" Margin="2" />

        <Button Grid.Row="2" Grid.Column="0" Name="Reset" Margin="2">Reset</Button>
        <Button Grid.Row="2" Grid.Column="1" Name="Submit" Margin="2">Submit</Button>
    </Grid>
</Window>

Az összes vezérlő hasonlóan hozható létre az XAML-ben. Ugyanez az ablak kódban is létrehozható:

// Grid container which is the content of the Window
Grid container = new() { Margin = new Thickness(5) };
container.RowDefinitions.Add(new RowDefinition());
container.RowDefinitions.Add(new RowDefinition());
container.RowDefinitions.Add(new RowDefinition());
container.ColumnDefinitions.Add(new ColumnDefinition());
container.ColumnDefinitions.Add(new ColumnDefinition());

// Create the two labels, assign the second label to the second row
Label labelName = new() { Content = "Enter your name:" };
container.Children.Add(labelName);

Label labelAddress = new() { Content = "Enter your address:" };
Grid.SetRow(labelAddress, 1);
container.Children.Add(labelAddress);

// Create the two textboxes, assign both to the second column and
// assign the second textbox to the second row.
TextBox textboxName = new() { Margin = new Thickness(2) };
Grid.SetColumn(textboxName, 1);
container.Children.Add(textboxName);

TextBox textboxAddress = new() { Margin = new Thickness(2) };
Grid.SetRow(textboxAddress, 1);
Grid.SetColumn(textboxAddress, 1);
container.Children.Add(textboxAddress);

// Create the two buttons, assign both to the third row and
// assign the second button to the second column.
Button buttonReset = new() { Margin = new Thickness(2), Content = "Reset" };
Grid.SetRow(buttonReset, 2);
container.Children.Add(buttonReset);

Button buttonSubmit = new() { Margin = new Thickness(2), Content = "Submit" };
Grid.SetColumn(buttonSubmit, 1);
Grid.SetRow(buttonSubmit, 2);
container.Children.Add(buttonSubmit);

// Create the popup window and assign the container (Grid) as its content
Window inputWindow = new()
{
    Title = "Input Record",
    Height = double.NaN,
    Width = 300,
    SizeToContent = SizeToContent.Height,
    Content = container
};

inputWindow.Show();
' Grid container which is the content of the Window
Dim container As New Grid() With {.Margin = New Thickness(5)}
container.RowDefinitions.Add(New RowDefinition())
container.RowDefinitions.Add(New RowDefinition())
container.RowDefinitions.Add(New RowDefinition())
container.ColumnDefinitions.Add(New ColumnDefinition())
container.ColumnDefinitions.Add(New ColumnDefinition())

' Create the two labels, assign the second label to the second row
Dim labelName As New Label() With {.Content = "Enter your name:"}
container.Children.Add(labelName)

Dim labelAddress As New Label() With {.Content = "Enter your address:"}
Grid.SetRow(labelAddress, 1)
container.Children.Add(labelAddress)

' Create the two textboxes, assign both to the second column and
' assign the second textbox to the second row.
Dim textboxName As New TextBox() With {.Margin = New Thickness(2)}
Grid.SetColumn(textboxName, 1)
container.Children.Add(textboxName)

Dim textboxAddress As New TextBox() With {.Margin = New Thickness(2)}
Grid.SetRow(textboxAddress, 1)
Grid.SetColumn(textboxAddress, 1)
container.Children.Add(textboxAddress)

' Create the two buttons, assign both to the third row and
' assign the second button to the second column.
Dim buttonReset As New Button() With {.Margin = New Thickness(2), .Content = "Reset"}
Grid.SetRow(buttonReset, 2)
container.Children.Add(buttonReset)

Dim buttonSubmit As New Button() With {.Margin = New Thickness(2), .Content = "Submit"}
Grid.SetColumn(buttonSubmit, 1)
Grid.SetRow(buttonSubmit, 2)
container.Children.Add(buttonSubmit)

' Create the window and assign the container (Grid) as its content
Dim inputWindow As New Window() With
{
    .Title = "Input Record",
    .Height = Double.NaN,
    .Width = 300,
    .SizeToContent = SizeToContent.Height,
    .Content = container
}

inputWindow.Show()

Feliratkozás az eseményekre

A vezérlő eseményére előfizethet XAML vagy kód használatával, de csak kódban kezelheti az eseményeket.

Az XAML-ben az esemény attribútumként van beállítva az elemen. Az események jelölésére nem használhatja a <Element.Event>handler<Element.Event> formátumot. Az alábbi kódrészlet bemutatja, hogyan iratkozhat fel egy Click eseményre Button:

<Button Click="Submit_Click" Grid.Row="2" Grid.Column="1" Name="Submit" Margin="2">Submit</Button>

A következő módon teheti ugyanezt a kódban:

Button buttonSubmit = new() { Margin = new Thickness(2), Content = "Submit" };
buttonSubmit.Click += Submit_Click;
Dim buttonSubmit As New Button() With {.Margin = New Thickness(2), .Content = "Submit"}
AddHandler buttonSubmit.Click, AddressOf Submit_Click

A következő kódrészlet kezeli a Click eseményét egy Button-nek.

private void Submit_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Someone clicked the submit button.");
}
Private Sub Submit_Click(sender As Object, e As Windows.RoutedEventArgs)
    MessageBox.Show("Someone clicked the submit button.")
End Sub

Vezérlőelem megjelenésének módosítása

Gyakran előfordul, hogy egy vezérlő megjelenése úgy változik, hogy illeszkedjen az alkalmazás megjelenéséhez és hangulatához. A vezérlők megjelenését az alábbiak egyikével módosíthatja, attól függően, hogy mit szeretne elérni:

  • Módosítsa a vezérlőelem egyik tulajdonságának értékét.
  • Hozzon létre egy Style a vezérléshez.
  • Hozzon létre egy új ControlTemplate vezérlőt.

Vezérlőelem tulajdonságának módosítása

Számos vezérlő rendelkezik olyan tulajdonságokkal, amelyekkel módosíthatja a vezérlő megjelenését, például egy gomb hátterét. Az értéktulajdonságokat az XAML-ben és a kódban is beállíthatja. Az alábbi példa XAML-ben állítja be a BackgroundFontSize, FontWeight és Button tulajdonságait.

<Button Grid.Row="2" Grid.Column="1" Name="Submit" Margin="2" Content="Submit">
    <Button.FontSize>18</Button.FontSize>
    <Button.FontWeight>Bold</Button.FontWeight>
    <Button.Background>
        <LinearGradientBrush>
            <GradientStop Color="#0073E6" Offset="0.0" />
            <GradientStop Color="#81D4FA" Offset="0.9" />
        </LinearGradientBrush>
    </Button.Background>
</Button>

A következő módon teheti ugyanezt a kódban:

Button buttonSubmit = new() { Margin = new Thickness(2), Content = "Submit" };
buttonSubmit.FontSize = 18f;
buttonSubmit.FontWeight = FontWeights.Bold;
buttonSubmit.Background =
    new LinearGradientBrush(
        (Color)ColorConverter.ConvertFromString("#0073E6"),
        (Color)ColorConverter.ConvertFromString("#81D4FA"),
        new Point(0d, 0d),
        new Point(0.9d, 0d));
Dim buttonSubmit As New Button() With {.Margin = New Thickness(2), .Content = "Submit"}
buttonSubmit.FontSize = 18.0F
buttonSubmit.FontWeight = FontWeights.Bold
buttonSubmit.Background =
        New LinearGradientBrush(
            ColorConverter.ConvertFromString("#0073E6"),
            ColorConverter.ConvertFromString("#81D4FA"),
            New Point(0D, 0D),
            New Point(0.9D, 0D))

A példaablak most a következő képhez hasonlóan néz ki:

Képernyőkép egy WPF-alkalmazásról két, névvel és címmel ellátott szövegmezővel. Két gomb látható. Az egyik gomb neve

Stílus létrehozása vezérlőelemhez

A WPF széles körű lehetőséget biztosít a vezérlők megjelenésének meghatározására úgy, hogy az egyes vezérlők tulajdonságai helyett egy-egy Styletulajdonságot hoz létre. Style definíciókat általában XAML-ben definiálják egy ResourceDictionary-ben, mint például egy vezérlő vagy ablak Resources tulajdonságában. Az erőforrások a deklarált hatókörre lesznek alkalmazva. További információ: XAML-erőforrások áttekintése.

Az alábbi példa minden olyan Style-ra alkalmaz egy Button-t, amelyeket egy ugyanabban a Grid-ban található elem határoz meg, amely definiálja a stílust.

<Grid.Resources>
    <Style TargetType="{x:Type Button}">
        <Style.Setters>
            <Setter Property="FontSize" Value="18" />
            <Setter Property="FontWeight" Value="Bold" />
            <Setter Property="Background">
                <Setter.Value>
                    <LinearGradientBrush>
                        <GradientStop Color="#0073E6" Offset="0.0" />
                        <GradientStop Color="#81D4FA" Offset="0.9" />
                    </LinearGradientBrush>
                </Setter.Value>
            </Setter>
        </Style.Setters>
    </Style>
</Grid.Resources>

A következő módon teheti ugyanezt a kódban:

Grid container = new() { Margin = new Thickness(5) };
container.RowDefinitions.Add(new RowDefinition());
container.RowDefinitions.Add(new RowDefinition());
container.RowDefinitions.Add(new RowDefinition());
container.ColumnDefinitions.Add(new ColumnDefinition());
container.ColumnDefinitions.Add(new ColumnDefinition());

Style buttonStyle = new(typeof(Button));
buttonStyle.Setters.Add(new Setter(Button.FontSizeProperty, 18d));
buttonStyle.Setters.Add(new Setter(Button.FontWeightProperty, FontWeights.Bold));
buttonStyle.Setters.Add(new Setter(Button.BackgroundProperty,
    new LinearGradientBrush(
        (Color)ColorConverter.ConvertFromString("#0073E6"),
        (Color)ColorConverter.ConvertFromString("#81D4FA"),
        new Point(0d, 0d),
        new Point(0.9d, 0d))));

container.Resources.Add(typeof(Button), buttonStyle);
Dim container As New Grid() With {.Margin = New Thickness(5)}
container.RowDefinitions.Add(New RowDefinition())
container.RowDefinitions.Add(New RowDefinition())
container.RowDefinitions.Add(New RowDefinition())
container.ColumnDefinitions.Add(New ColumnDefinition())
container.ColumnDefinitions.Add(New ColumnDefinition())

Dim buttonStyle As New Style(GetType(Button))
buttonStyle.Setters.Add(New Setter(Button.FontSizeProperty, 18.0R))
buttonStyle.Setters.Add(New Setter(Button.FontWeightProperty, FontWeights.Bold))
buttonStyle.Setters.Add(New Setter(Button.BackgroundProperty,
        New LinearGradientBrush(
            ColorConverter.ConvertFromString("#0073E6"),
            ColorConverter.ConvertFromString("#81D4FA"),
            New Point(0D, 0D),
            New Point(0.9D, 0D))))

container.Resources.Add(GetType(Button), buttonStyle)

Az alábbi képen az ablak rácsára alkalmazott stílus látható, amely megváltoztatja a két gomb megjelenését:

Képernyőkép egy WPF-alkalmazásról két, névvel és címmel ellátott szövegmezővel. Két gomb látható. Az egyik gomb neve

Ahelyett, hogy a stílust egy adott típusú vezérlőre alkalmazták, az adott vezérlőkhöz is hozzárendelhetők úgy, hogy hozzáadnak egy kulcsot a stílushoz az erőforrás-szótárban, és hivatkoznak rá a Style vezérlő tulajdonságában. A stílusokról további információt a Stílus és a Templatingcímű témakörben talál.

ControlTemplate létrehozása

A Style lehetővé teszi, hogy egyszerre több vezérlőn is beállítson tulajdonságokat, de néha előfordulhat, hogy a vezérlő megjelenését szeretné a Style által kínált lehetőségeken túlmenően testre szabni. Az Control osztályból öröklődő osztályok rendelkeznek egy ControlTemplate, amely meghatározza a vezérlő szerkezetét és megjelenését.

Vegye figyelembe a Button vezérlőt, amelyet szinte minden alkalmazás használ. A gomb elsődleges viselkedése az, hogy lehetővé teszi az alkalmazások számára, hogy bizonyos műveletet hajthassanak végre, amikor a felhasználó kiválasztja a gombot. Alapértelmezés szerint a WPF gombja emelt téglalapként jelenik meg. Egy alkalmazás fejlesztése során érdemes lehet kihasználni egy gomb viselkedését – vagyis azt, hogyan lép kapcsolatba a felhasználó a gombbal, ami Click eseményt hozhat létre –, ugyanakkor a gomb megjelenését esetleg úgy szeretné megváltoztatni, hogy az túllép a gomb tulajdonságainak módosításával elérhető határokon. Ebben az esetben létrehozhat egy újat ControlTemplate.

Az alábbi példa létrehoz egy ControlTemplate egy Button számára. Ez a ControlTemplate egy vizuális képet hoz létre a Button számára, amely egy lekerekített sarkokkal és színátmenetes háttérrel rendelkező szegélyt jelenít meg.

<Button Grid.Row="2" Grid.Column="1" Name="Submit" Margin="2" Content="Submit">
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border Name="Border" CornerRadius="10" 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="PeachPuff" 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="LightBlue" Offset="0.9" />
                            </LinearGradientBrush>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </Button.Template>
</Button>

Megjegyzés:

A Background tulajdonságot be kell állítani egy Button értékre, hogy a SolidColorBrush példa megfelelően működjön.

És a következőképpen teheti ugyanezt a kódban. Az alábbi kód létrehoz egy XAML-sztringet, és elemzi egy alkalmazható sablon létrehozásához, amely a sablon futásidőben történő létrehozásának támogatott módja.

Button buttonSubmit = new() { Margin = new Thickness(2), Content = "Submit" };

// Create the XAML used to define the button template
const string xaml = """
    <ControlTemplate TargetType="Button">
        <Border Name="Border" CornerRadius="10" 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="PeachPuff" 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="LightBlue" Offset="0.9" />
                        </LinearGradientBrush>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>
    """;

// Load the XAML into a stream that can be parsed
using MemoryStream stream = new(System.Text.Encoding.UTF8.GetBytes(xaml));

// Create a parser context and add the default namespace and 
// the x namespace, which is common to WPF XAML
System.Windows.Markup.ParserContext context = new();
context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");

// Parse the XAML and assign it to the button's template
buttonSubmit.Template = (ControlTemplate)System.Windows.Markup.XamlReader.Load(stream, context);

// Set the other properties of the button
Grid.SetColumn(buttonSubmit, 1);
Grid.SetRow(buttonSubmit, 2);

// Assign the button to the grid container
container.Children.Add(buttonSubmit);
Dim buttonSubmit As New Button() With {.Margin = New Thickness(2), .Content = "Submit"}

' Create the XAML used to define the button template
Const xaml As String = "
    <ControlTemplate TargetType=""Button"">
        <Border Name=""Border"" CornerRadius=""10"" 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=""PeachPuff"" 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=""LightBlue"" Offset=""0.9"" />
                        </LinearGradientBrush>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </ControlTemplate.Triggers>
    </ControlTemplate>"

' Load the XAML into a stream that can be parsed
Using stream As New MemoryStream(System.Text.Encoding.UTF8.GetBytes(xaml))

    ' Create a parser context and add the default namespace and 
    ' the x namespace, which is common to WPF XAML
    Dim context = New System.Windows.Markup.ParserContext()
    context.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation")
    context.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml")

    ' Parse the XAML and assign it to the button's template
    buttonSubmit.Template = System.Windows.Markup.XamlReader.Load(stream, context)
End Using

' Set the other properties of the button
Grid.SetColumn(buttonSubmit, 1)
Grid.SetRow(buttonSubmit, 2)

' Assign the button to the grid container
container.Children.Add(buttonSubmit)

Az alábbi képen látható, hogy a sablon hogyan néz ki alkalmazásakor:

Képernyőkép egy WPF-alkalmazásról két, névvel és címmel ellátott szövegmezővel. Két gomb látható. Az egyik gomb neve

Az előző példában a rendszer egyetlen gombra alkalmazza a ControlTemplate elemet. Azonban egy ControlTemplate hozzárendelhető egy Style elemhez, és alkalmazható az összes gombra, amivel, ahogy az a vezérlőnek stílus létrehozása szakaszban bemutatottak szerint történt.

A sablon által nyújtott egyedi funkciók előnyeinek kihasználásáról további információt a Stílus és a Templating című témakörben talál.

Gazdag tartalom a vezérlőkben

Az Control osztályból öröklő osztályok többsége képes gazdag tartalom befogadására. Például egy Label bármilyen objektumot tartalmazhat, mint egy sztring, egy Image, vagy egy Panel. A következő osztályok támogatják a gazdag tartalmakat, és alaposztályként működnek a WPF legtöbb vezérlője számára: