Not
Bu sayfaya erişim yetkilendirme gerektiriyor. Oturum açmayı veya dizinleri değiştirmeyi deneyebilirsiniz.
Bu sayfaya erişim yetkilendirme gerektiriyor. Dizinleri değiştirmeyi deneyebilirsiniz.
Windows Presentation Foundation (WPF), Button, Label, TextBox, Menu ve ListBox gibi hemen her Windows uygulamasında kullanılan birçok ortak kullanıcı arabirimi bileşeni ile birlikte gelir. Geçmişte bu nesneler denetim olarak adlandırılır. "denetim" terimi, bir uygulamadaki görünür nesneyi temsil eden herhangi bir sınıf anlamına gelen gevşek bir şekilde kullanılır. Sınıfın görünür bir özellik kazanması için Control sınıfından miras almasına gerek olmadığını belirtmek önemlidir.
Control sınıfından devralan sınıflar, bir denetimin tüketicisinin yeni bir alt sınıf oluşturmak zorunda kalmadan denetimin görünümünü kökten değiştirmesine olanak tanıyan bir ControlTemplateiçerir. Bu makalede denetimlerin (hem sınıfından Control devralınanlar hem de devralmayanlar) WPF'de yaygın olarak nasıl kullanıldığı açıklanır.
Denetimin örneğini oluşturma
Genişletilebilir Uygulama Biçimlendirme Dili (XAML) veya kod kullanarak uygulamaya denetim ekleyebilirsiniz. Örneğin, kullanıcıdan adını ve adresini isteyen wpf penceresinin aşağıdaki görüntüsünü göz önünde bulundurun:
Bu pencerede altı denetim vardır: iki etiket, iki metin kutusu ve iki düğme. XAML, aşağıdaki kod parçacığında gösterildiği gibi bu denetimleri oluşturmak için kullanılır:
<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>
Tüm denetimler XAML'de benzer şekilde oluşturulabilir. Kodda aynı pencere oluşturulabilir:
// 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()
Olaylara Abone Olma
Bir denetimin olayına XAML veya kod kullanarak abone olabilirsiniz, ancak bir olayı yalnızca kodda işleyebilirsiniz.
XAML'de olay öğesinde bir öznitelik olarak ayarlanır.
<Element.Event>handler<Element.Event> gösterimini olaylar için kullanamazsınız. Aşağıdaki kod parçacığında, bir Click olayına nasıl abone olunacağını Button gösterilmektedir:
<Button Click="Submit_Click" Grid.Row="2" Grid.Column="1" Name="Submit" Margin="2">Submit</Button>
Kodda da aynı işlemi şu şekilde yapabilirsiniz:
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şağıdaki kod parçacığı bir Clickolayını işlerButton:
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
Denetimin görünümünü değiştirme
Bir denetimin görünümünü uygulamanızın genel görünümüne uyacak şekilde değiştirmek yaygındır. Gerçekleştirmek istediğiniz şeye bağlı olarak aşağıdakilerden birini yaparak denetimin görünümünü değiştirebilirsiniz:
- Denetimin bir özelliğinin değerini değiştirin.
- Denetim için bir Style oluşturun.
- Denetim için yeni bir ControlTemplate oluşturun.
Denetimin özelliğini değiştirme
Birçok denetim, düğmenin arka planı gibi denetimin görünümünü değiştirmenizi sağlayan özelliklere sahiptir. Hem XAML hem de kodda değer özelliklerini ayarlayabilirsiniz. Aşağıdaki örnek, XAML'de Backgroundüzerinde FontSize , FontWeightve Button özelliklerini ayarlar:
<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>
Kodda da aynı işlemi şu şekilde yapabilirsiniz:
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))
Örnek pencere şimdi aşağıdaki görüntüye benzer:
Denetim için stil oluşturma
WPF, her denetimde özellikleri ayarlamak yerine bir Styleoluşturarak denetimlerin görünümünü belirtmenizi sağlar.
Style tanımları genellikle XAML'de bir ResourceDictionary içinde, bir denetimin Resources özelliği veya pencere özelliği olarak tanımlanır. Kaynaklar, tanımlandığı kapsama uygulanmaktadır. Daha fazla bilgi için bkz. XAML kaynaklarına genel bakış.
Aşağıdaki örnek, stili tanımlayan aynı Style içindeki her Button bir öğeye bir Grid uygular:
<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>
Kodda da aynı işlemi şu şekilde yapabilirsiniz:
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)
Aşağıdaki görüntüde, pencerenin kılavuzuna uygulanan ve iki düğmenin görünümünü değiştiren stil gösterilmektedir:
Belirli bir türün tüm denetimlerine stili uygulamak yerine, kaynak sözlüğüne stile özel bir anahtar ekleyip ve denetimin Style özelliğinde bu anahtara başvurarak stili belirli denetimlere de atanabilir. Stiller hakkında daha fazla bilgi için bkz. Stil ve Şablon.
ControlTemplate oluşturma
A Style , aynı anda birden çok denetimde özellik ayarlamanıza olanak tanır, ancak bazen denetimin görünümünü ile Styleyapabileceklerinin ötesinde özelleştirmek isteyebilirsiniz.
Control sınıfından devralan sınıfların, bir denetimin yapısını ve görünümünü tanımlayan bir ControlTemplate öğesi vardır.
Neredeyse tüm uygulamalar tarafından kullanılan ortak bir denetim olan Button denetimini göz önünde bulundurun. Bir düğmenin birincil davranışı, kullanıcı düğmeyi seçtiğinde uygulamanın bazı eylemler gerçekleştirmesini sağlamaktır. Varsayılan olarak, WPF'deki düğme yükseltilmiş bir dikdörtgen olarak görünür. Uygulama geliştirirken, bir düğmenin davranışından (yani kullanıcının bir olayı tetikleyen Click düğmeyle nasıl etkileşimde bulunduğundan) yararlanmak isteyebilirsiniz, ancak düğmenin özelliklerini değiştirerek düğmenin görünümünü yapabileceklerinin ötesinde değiştirebilirsiniz. Bu durumda, yeni bir ControlTemplateoluşturabilirsiniz.
Aşağıdaki örnek, ControlTemplateiçin bir Button oluşturur.
ControlTemplate, Button için yuvarlatılmış köşeler ve gradyan arka plana sahip bir kenarlık sunan bir görsel oluşturur.
<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>
Uyarı
Örneğin düzgün çalışması için Background'in Button özelliği bir SolidColorBrush'ye ayarlanmalıdır.
Kodda da aynı işlemi şu şekilde yapabilirsiniz. Aşağıdaki kod bir XAML dizesi oluşturur ve bunu ayrıştırarak uygulanabilen bir şablon oluşturur. Bu, çalışma zamanında şablon oluşturmanın desteklenen yoludur.
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)
Aşağıdaki görüntüde, şablon uygulandığında nasıl göründüğü gösterilmektedir:
Önceki örnekte, ControlTemplate tek bir düğmeye uygulanır. Ancak, ControlTemplate bir Style'e atanabilir ve Denetim için stil oluşturma bölümünde nasıl gösterildiği gibi tüm düğmelere uygulanabilir.
Şablonun sağladığı benzersiz özelliklerden yararlanma hakkında daha fazla bilgi için bkz. Stil Oluşturma ve Şablon Oluşturma.
Denetimlerdeki zengin içerik
Control sınıfından devralan sınıfların çoğu zengin içerik içerebilecek kapasiteye sahiptir. Örneğin, bir Label dize, Imageveya Panelgibi herhangi bir nesne içerebilir. Aşağıdaki sınıflar zengin içerik için destek sağlar ve WPF'deki denetimlerin çoğu için temel sınıflar olarak hareket eder:
ContentControl—Bu sınıftan Labeldevralan sınıflara örnek olarak , Buttonve ToolTipverilebilir.
ItemsControl—Bu sınıftan ListBoxdevralan sınıflara örnek olarak , Menuve StatusBarverilebilir.
HeaderedContentControl—Bu sınıftan TabItemdevralan sınıflara örnek olarak , GroupBoxve Expanderverilebilir.
HeaderedItemsControl—Bu sınıftan MenuItemdevralan sınıflara örnek olarak , TreeViewItemve ToolBarverilebilir.
İlgili içerik
.NET Desktop feedback