WPF Development, Add Control

Windows Presentation Foundation (WPF) is a technology provided for creating rich user interfaces in the .NET framework. Using WPF, you can integrate graphics, text, video, and more to build appealing user interfaces. This article details how to add controls in WPF and practice the concepts of WPF through actual example code.

What is WPF?

WPF supports defining UI using XAML (Extensible Application Markup Language) and writing business logic in .NET languages like C#. The main advantages of WPF are as follows:

  • Data Binding: Allows binding between the UI and business data.
  • Templates and Styles: Provides flexible customization of the visual representation of various UI elements.
  • 3D Graphics Support: WPF supports 3D graphics, enabling the creation of more diverse UIs.
  • Direct Hardware Acceleration: WPF leverages GPU acceleration for better performance.

Adding Controls in WPF

To create a WPF application, you need to use a development environment like Visual Studio. The following steps show how to create a simple WPF application and add various basic controls.

1. Create a WPF Project

  1. Open Visual Studio and click “Create a new project.”
  2. Select “WPF App (.NET Core)” from the template list and click “Next.”
  3. After setting the project name and path, click “Create.”

2. Understanding the XAML File

The UI of a WPF application is defined in XAML files. The generated project typically includes App.xaml and MainWindow.xaml files. The MainWindow.xaml file contains the basic layout where various controls can be added.


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

    </Grid>
</Window>

3. Adding Basic Controls

Now it’s time to add various controls inside the Grid layout. Commonly used basic controls in WPF include Button, TextBox, Label, and ComboBox.

Adding a Button Control


<Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>

Adding a TextBox Control


<TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>

Adding a Label Control


<Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0"/>

Adding a ComboBox Control


<ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,150,0,0">
    <ComboBoxItem Content="Option 1"/>
    <ComboBoxItem Content="Option 2"/>
    <ComboBoxItem Content="Option 3"/>
</ComboBox>

4. Full Code of the XAML File

Here is the complete code of the MainWindow.xaml file including all the added controls:


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0"/>
        <TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>
        <Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>
        <ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,150,0,0">
            <ComboBoxItem Content="Option 1"/>
            <ComboBoxItem Content="Option 2"/>
            <ComboBoxItem Content="Option 3"/>
        </ComboBox>
    </Grid>
</Window>

5. Implementing C# Code Behind

Let’s now add C# code to handle the button click event. Open the MainWindow.xaml.cs file and add code that displays the name when the button is clicked.


using System.Windows;

namespace MyWpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            string name = myTextBox.Text;
            if (!string.IsNullOrEmpty(name))
            {
                MessageBox.Show("Hello, " + name + "!");
            }
            else
            {
                MessageBox.Show("Please enter your name.");
            }
        }
    }
}

6. Running the Application

Now press the F5 key to run the application. Enter a name in the input box and click the “Click Me” button, and a welcoming message will display with the entered name. This is an example of basic UI interaction in WPF.

7. Adding Various Controls

In this section, we will look at several additional controls available in WPF. This section explains how to add DataGrid, ListBox, CheckBox, and RadioButton.

Adding a DataGrid

The DataGrid is a control that is useful for displaying and editing large amounts of data. Let’s add a DataGrid as follows:


<DataGrid Name="myDataGrid" AutoGenerateColumns="False" Width="400" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,200,0,0">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
        <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
    </DataGrid.Columns>
</DataGrid>

Adding a ListBox

The ListBox displays a list of items and allows selection.


<ListBox Name="myListBox" Width="200" Height="100" HorizontalAlignment="Right" VerticalAlignment="Top">
    <ListBoxItem Content="Item 1"/>
    <ListBoxItem Content="Item 2"/>
    <ListBoxItem Content="Item 3"/>
</ListBox>

Adding a CheckBox

The CheckBox provides an option that users can select or deselect.


<CheckBox Name="myCheckBox" Content="Check me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,320,0,0"/>

Adding a RadioButton

The RadioButton allows users to select only one option among multiple choices.


<StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Top">
    <RadioButton Name="option1" Content="Option 1" GroupName="Options"/>
    <RadioButton Name="option2" Content="Option 2" GroupName="Options"/>
</StackPanel>

8. Updated Full Code of the XAML File

The complete code of the MainWindow.xaml file including all the discussed controls is as follows:


<Window x:Class="MyWpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="400" Width="525">
    <Grid>
        <Label Content="Enter your name:" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,10,0,0"/>
        <TextBox Name="myTextBox" Width="200" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,50,0,0"/>
        <Button Name="myButton" Content="Click Me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Click="MyButton_Click"/>

        <ComboBox Name="myComboBox" Width="120" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,100,0,0">
            <ComboBoxItem Content="Option 1"/>
            <ComboBoxItem Content="Option 2"/>
            <ComboBoxItem Content="Option 3"/>
        </ComboBox>

        <DataGrid Name="myDataGrid" AutoGenerateColumns="False" Width="400" Height="200" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,200,0,0">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
                <DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
            </DataGrid.Columns>
        </DataGrid>

        <ListBox Name="myListBox" Width="200" Height="100" HorizontalAlignment="Right" VerticalAlignment="Top">
            <ListBoxItem Content="Item 1"/>
            <ListBoxItem Content="Item 2"/>
            <ListBoxItem Content="Item 3"/>
        </ListBox>

        <CheckBox Name="myCheckBox" Content="Check me" Width="100" Height="30" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0,320,0,0"/>

        <StackPanel Orientation="Vertical" HorizontalAlignment="Left" VerticalAlignment="Top">
            <RadioButton Name="option1" Content="Option 1" GroupName="Options"/>
            <RadioButton Name="option2" Content="Option 2" GroupName="Options"/>
        </StackPanel>
    </Grid>
</Window>

9. Data Binding

One of the powerful features of WPF is data binding. Data binding allows you to connect the UI with data, and when the data changes, the UI is automatically updated.

Creating a Model Class

First, let’s create a model class. Create a new class and set its name to Person.


public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

Setting up the ViewModel

The ViewModel provides the data to be displayed on the UI. In the MainWindow.xaml.cs file, we will use ObservableCollection to manage the data.


using System.Collections.ObjectModel;

namespace MyWpfApp
{
    public partial class MainWindow : Window
    {
        public ObservableCollection<Person> People { get; set; }

        public MainWindow()
        {
            InitializeComponent();
            
            People = new ObservableCollection<Person>();
            People.Add(new Person { Name = "Alice", Age = 28 });
            People.Add(new Person { Name = "Bob", Age = 32 });

            myDataGrid.ItemsSource = People;
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            string name = myTextBox.Text;
            if (!string.IsNullOrEmpty(name))
            {
                People.Add(new Person { Name = name, Age = 0 });
                myTextBox.Clear();
            }
        }
    }
}

10. Updating Data in the DataGrid

Now users can modify the data in the DataGrid, and the changes will be automatically reflected in the ObservableCollection. In the example, the user will add names to the list.

Conclusion

This post covered how to add and use various controls in WPF. We addressed basic UI components, data binding, and data management in the data grid, highlighting how to utilize the powerful features of WPF.

Next Steps

If you want to delve deeper into WPF, I recommend studying styles, templates, the MVVM pattern, asynchronous programming, and how to connect to databases. WPF has various possibilities, and you can create more attractive applications depending on your imagination.

In the next post, I will introduce how to create custom controls in WPF. Thank you!

This article was written by [Your Name].

WPF Development, Control Status

Windows Presentation Foundation (WPF) is a powerful platform that is part of the .NET Framework for building complex user interfaces. In WPF, managing the states of controls plays an important role for developers when creating user interfaces. This article will detail how to manage control states in WPF along with example code.

1. Overview of State Management in WPF

WPF provides various methods to manage the state of each control. A state refers to the visual representation of a control that can change based on user actions or the state of the UI. For instance, a button control has a normal state, a hover state when the mouse is over it, and a pressed state when clicked.

2. Notation and Programming of States

In WPF, you can define and transition control states using the Visual State Manager (VSM). By using the VSM, states can be visually defined and transitions can be implemented as animations. The following is an example of how to set the state of a button using VSM.

2.1 Visual State Manager Example



In this example, the button’s states are defined as Normal, MouseOver, and Pressed. Each state is given animation effects using the Storyboard.

3. Custom States

In WPF, you can create custom states in addition to those provided by default controls. This is particularly useful for creating complex custom controls. The following example shows how to add states to a custom control.

3.1 Custom Control Example


public class CustomButton : Button
{
    static CustomButton()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomButton), new FrameworkPropertyMetadata(typeof(CustomButton)));
    }

    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        VisualStateManager.GoToState(this, "Normal", true);
    }

    private void OnMouseEnter(object sender, MouseEventArgs e)
    {
        VisualStateManager.GoToState(this, "MouseOver", true);
    }

    private void OnMouseLeave(object sender, MouseEventArgs e)
    {
        VisualStateManager.GoToState(this, "Normal", true);
    }

    protected override void OnClick()
    {
        VisualStateManager.GoToState(this, "Pressed", true);
        base.OnClick();
    }
}

This class is implemented to allow the button to transition to different visual states based on mouse state while maintaining its basic functionality. Each state transition is handled using VisualStateManager.

4. States and Data Binding

In WPF, states can be combined with data to dynamically update the UI. By changing states through data binding, the UI is immediately updated. The following is an example of state management using data binding.

4.1 Data Binding Example



    
        
        
    


public partial class MainWindow : Window, INotifyPropertyChanged
{
    private string status;
    public string Status
    {
        get => status;
        set
        {
            status = value;
            OnPropertyChanged("Status");
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        Status = "The button has been clicked.";
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

In the example above, every time the button is clicked, the Status property changes, and that change is immediately reflected in the UI. Through data binding, control states can be effectively managed.

5. Complex State Management

Sometimes, not only simple states but also complex transitions and animations may be required. WPF can utilize the Visual State Manager for these cases as well. By combining complex states and animations, you can enhance the user’s experience.

5.1 Complex State Example



    
        
            
                
                    
                        
                    
                
                
                    
                        
                    
                
            
        
        
    

This custom control has two states (StateA, StateB) and animates the opacity of a Rectangle in each state.

6. Summary

Managing control states in WPF is an important element that enhances the user experience. By utilizing the Visual State Manager, you can easily manage the states of each control and express state transitions as animations. Creating custom controls and dynamically updating the UI through data binding are key techniques in WPF development.

Through this article, you have gained an understanding of the concepts of control state management in WPF and explored various practical methods. This knowledge will be very useful when developing complex applications.

WPF Development, Change Control Appearance

Windows Presentation Foundation (WPF) is a powerful platform that is part of the .NET framework, allowing for the creation of rich user interfaces. One of the biggest advantages of WPF is that it provides a variety of UI controls and enables easy design and styling of them. This article will detail various ways to change the appearance of controls in WPF.

Basic Structure of WPF Controls

WPF controls are defined in XAML (Extensible Application Markup Language). XAML is a language that allows you to declaratively code user interfaces. Let’s look at various controls provided by WPF, such as Button, TextBox, and ComboBox.

Example: Basic Button

<Button Name="myButton" Content="Click Me!" />

The above XAML is code that creates a basic button. By default, styles are applied depending on the system theme.

Changing Control Styles

The most common way to change the appearance of controls in WPF is to use styles. Styles are XAML objects used to define the visual characteristics of a specific control.

Defining a Style

Styles can be defined within the Window.Resources or Application.Resources elements. Below is an example of a style that changes the background color and font of a button.

Example: Button Style


<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="200" Width="300">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Background" Value="LightBlue"/>
            <Setter Property="Foreground" Value="DarkBlue"/>
            <Setter Property="FontSize" Value="16"/>
        </Style>
    </Window.Resources>

    <Grid>
        <Button Content="Button with Style" />
    </Grid>
</Window>

The above code sets the background color of all buttons to LightBlue and the foreground color to DarkBlue. By defining a style in this way, developers do not need to set the properties of the button separately; the style is applied automatically.

Using Control Triggers

Triggers allow you to dynamically change styles when certain conditions are met. For example, you can add a trigger that changes the color when the mouse hovers over a button.

Example: Mouse Over Trigger


<Style TargetType="Button">
    <Setter Property="Background" Value="LightBlue"/>
    <Setter Property="Foreground" Value="DarkBlue"/>
    <Setter Property="FontSize" Value="16"/>

    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="DarkBlue"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
</Style>

In the above code, when the IsMouseOver property is true, the button’s background color and foreground color change. Triggers are a very useful tool for enhancing user experience.

Customization Using ControlTemplate

If you want to specify the appearance of a control more precisely, you can use ControlTemplate. A ControlTemplate defines the internal structure of a control, allowing you to replace the provided visual elements with completely different shapes.

Example: Changing Button ControlTemplate


<Style TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border Background="{TemplateBinding Background}" 
                        BorderBrush="Black" 
                        BorderThickness="2" 
                        CornerRadius="10">
                    <ContentPresenter HorizontalAlignment="Center" 
                                      VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

When this style is applied to a button, the default button shape disappears, and the content is displayed within a Border element with rounded corners. The button’s background color is bound to the custom style through TemplateBinding.

Styling List Items through Data Templates

In WPF, you can use data templates to define the presentation of items in controls like ItemsControl, ListBox, and ComboBox. By using data templates, you can freely place all UI elements needed to visually represent complex data.

Example: Using Data Templates


<Window.Resources>
    <DataTemplate x:Key="PersonTemplate">
        <StackPanel Orientation="Horizontal">
            <Ellipse Width="30" Height="30" Fill="LightGreen"/>
            <TextBlock Text="{Binding Name}" Margin="5" FontSize="14"/>
        </StackPanel>
    </DataTemplate>
</Window.Resources>

<ListBox ItemTemplate="{StaticResource PersonTemplate}">
    <ListBoxItem Content="{Binding Name='Hong Gil-dong'}"/>
    <ListBoxItem Content="{Binding Name='Lee Sun-shin'}"/>
</ListBox>

In the above example, the DataTemplate defines each data item with a StackPanel, displaying a circular graphic along with the item’s name. This effectively connects data and UI for representation.

Adding Visual Effects through Animation

WPF supports easy addition of animations through XAML. By incorporating animations, you can enrich the user experience.

Example: Button Animation


<Button Name="myAnimatedButton" Content="Animated Button">
    <Button.Resources>
        <Storyboard x:Key="MyAnimation">
            <DoubleAnimation 
                Storyboard.TargetProperty="Opacity"
                From="1" To="0.5" Duration="0:0:1" 
                AutoReverse="True"
                RepeatBehavior="Forever"/>
        </Storyboard>
    </Button.Resources>
    <Button.Triggers>
        <EventTrigger RoutedEvent="Button.MouseEnter">
            <BeginStoryboard Storyboard="{StaticResource MyAnimation}" />
        </EventTrigger>
    </Button.Triggers>
</Button>

This code applies an Opacity animation to the button when the mouse hovers over it, giving a faded effect as it becomes semi-transparent and then reappears. Using animations, you can create aesthetically appealing UIs.

Conclusion

WPF is a powerful and flexible tool for designing user interfaces in various ways. Through fundamental styles, triggers, templates, data templates, and animations, developers can enhance user experience and build more beautiful interfaces. As you continue developing in WPF, consider utilizing various styles and templates. These techniques will ultimately contribute to creating better software.

WPF Development, Events

WPF (Windows Presentation Foundation) is a powerful and flexible tool used to create Windows applications. It provides various elements for constructing the user interface (UI), and these elements utilize events to respond to user interactions. This article will take a deep dive into the event system of WPF and help you gain practical understanding through example code.

What is an Event?

An event is a notification of a specific action or state change that occurs from a user or the system. In WPF, various elements (buttons, text boxes, etc.) can raise specific events, and developers can register listeners (handlers) for these events to respond to user inputs or system actions.

WPF Event Model

WPF is primarily based on the .NET event model and includes the following two main elements:

  • Events: Signals that represent interactions between the user and the system.
  • Event Handlers: Methods that execute when a specific event occurs.

The WPF event model has the following form:

 
public event EventHandler MyEvent;

In the above code, MyEvent is a user-defined event, and EventHandler is a built-in delegate. Generally, events are called when a specific situation occurs (clicking, mouse movement, etc.).

Using Events in WPF

To use events in WPF, you follow these two steps:

  1. Raising Events: WPF UI elements (buttons, checkboxes, etc.) provide various events, and developers can add these events to UI elements.
  2. Registering Event Handlers: Implement methods that define the actions to be performed when an event occurs and connect them to the event.

Event Example

In this example, we will create a simple WPF application that outputs a message when the user clicks a button.

XAML Code

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="WPF Event Example" Height="200" Width="300">
    <Grid>
        <Button Name="myButton" Content="Please Click" Click="MyButton_Click" Width="200" Height="100" />
    </Grid>
</Window>

C# Code

using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("The button has been clicked!");
        }
    }
}

In the above code, the MyButton_Click method is called when the button is clicked. The MessageBox.Show function informs the user that the button has been clicked.

Event Arguments

In WPF, event handlers typically have two parameters:

  • sender: The object that raised the event.
  • e: An object that contains data about the event.

An example of utilizing event arguments is as follows:

private void MyButton_Click(object sender, RoutedEventArgs e)
{
    Button clickedButton = sender as Button;
    MessageBox.Show(clickedButton.Content + " button has been clicked!");
}

Handling Multiple Events

It is possible to handle various events of different UI elements within a single method. Let’s examine this through the example below.

XAML Code

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Handling Various Events" Height="250" Width="250">
    <StackPanel>
        <Button Name="button1" Content="Button 1" Click="AnyButton_Click" Width="100" Height="30" />
        <Button Name="button2" Content="Button 2" Click="AnyButton_Click" Width="100" Height="30" />
        <Button Name="button3" Content="Button 3" Click="AnyButton_Click" Width="100" Height="30" />
    </StackPanel>
</Window>

C# Code

using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void AnyButton_Click(object sender, RoutedEventArgs e)
        {
            Button clickedButton = sender as Button;
            MessageBox.Show(clickedButton.Content + " has been clicked.");
        }
    }
}

In the above example, there are three buttons, each registered with the same event handler (AnyButton_Click). When the user clicks a button, the name of that button is displayed in a message box.

Removing Events

Event handlers can be removed as needed. Below is a simple example that removes an event handler.

XAML Code

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Event Removal Example" Height="200" Width="300">
    <StackPanel>
        <Button Name="myButton" Content="Please Click" Click="AddClick" Width="200" Height="100" />
        <Button Name="removeButton" Content="Remove Event" Click="RemoveClick" Width="200" Height="100" />
    </StackPanel>
</Window>

C# Code

using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void AddClick(object sender, RoutedEventArgs e)
        {
            myButton.Click += MyButton_Click;
            MessageBox.Show("The event has been added.");
        }

        private void RemoveClick(object sender, RoutedEventArgs e)
        {
            myButton.Click -= MyButton_Click;
            MessageBox.Show("The event has been removed.");
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("The button has been clicked!");
        }
    }
}

The above code demonstrates how to dynamically add and remove events when the user clicks a button. The += symbol is used to add an event handler, and the -= symbol is used to remove it.

Creating Custom Events

Developers can create custom events for WPF elements. To do this, the event keyword is used to define a new event.

public class MyButton : Button
{
    public event RoutedEventHandler MyCustomEvent;

    protected virtual void OnMyCustomEvent()
    {
        MyCustomEvent?.Invoke(this, new RoutedEventArgs());
    }

    protected override void OnClick()
    {
        base.OnClick();
        OnMyCustomEvent();
    }
}

The above code defines a custom button class that raises MyCustomEvent when clicked by the user. When the button is clicked, MyCustomEvent is triggered.

Conclusion

In WPF, events are a crucial element for handling user interactions. By understanding events and event handlers, developers can build more interactive and responsive applications. This article has practiced the basic event system, event handling, and creation of custom events, demonstrating how to implement smooth interactions between users and applications.

Continue to learn about the various events and their usages provided by WPF and try to apply them in your projects. Happy Coding!

WPF Development, Practice Display Products and Details

WPF (Windows Presentation Foundation) is a powerful UI framework based on the .NET Framework. It is particularly well-suited for developing desktop applications. In this course, we will learn how to display product lists and information details using WPF. Topics covered in this course include product data binding, implementing the MVVM (Model-View-ViewModel) pattern, and UI design using XAML.

1. Preparation Tasks

To create a WPF application, you must first install Visual Studio and create a new WPF application project. Let’s set up the new project by following the steps below.

  1. Launch Visual Studio.
  2. In the File menu, select New -> Project.
  3. From the project templates, select WPF App (.NET Core) or WPF App (.NET Framework).
  4. Specify the project name and storage path, then click Create.

2. Understanding the MVVM Pattern

The MVVM (Model-View-ViewModel) pattern is an architecture pattern primarily used in WPF that helps to separate the user interface (UI) from business logic. The three components of this pattern are as follows:

  • Model: Business logic and data.
  • View: User interface.
  • ViewModel: Mediator between View and Model.

In this course, we will create a simple product information application while applying the MVVM pattern.

3. Creating Data Model

First, let’s create a Product class to hold product information. This class will have properties for the product’s name, price, and description.

using System.ComponentModel;

public class Product : INotifyPropertyChanged
{
    private string _name;
    private decimal _price;
    private string _description;

    public string Name
    {
        get => _name;
        set
        {
            _name = value;
            OnPropertyChanged(nameof(Name));
        }
    }

    public decimal Price
    {
        get => _price;
        set
        {
            _price = value;
            OnPropertyChanged(nameof(Price));
        }
    }

    public string Description
    {
        get => _description;
        set
        {
            _description = value;
            OnPropertyChanged(nameof(Description));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

The above code implements the INotifyPropertyChanged interface to allow notifications when properties change. This is useful for data binding.

4. Creating ViewModel

Next, we will create a ProductViewModel class to implement the logic that manages the product list. This ViewModel includes a list of products and displays the details of the selected product.

using System.Collections.ObjectModel;
using System.Windows.Input;

public class ProductViewModel : INotifyPropertyChanged
{
    private Product _selectedProduct;

    public ObservableCollection<Product> Products { get; }

    public Product SelectedProduct
    {
        get => _selectedProduct;
        set
        {
            _selectedProduct = value;
            OnPropertyChanged(nameof(SelectedProduct));
        }
    }

    public ProductViewModel()
    {
        Products = new ObservableCollection<Product>
        {
            new Product { Name = "Laptop", Price = 1200000, Description = "High-performance laptop." },
            new Product { Name = "Smartphone", Price = 800000, Description = "Latest smartphone." },
            new Product { Name = "Tablet", Price = 500000, Description = "Portable tablet." }
        };
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here, we use ObservableCollection<Product> to manage the product list. ObservableCollection automatically reflects changes in the collection in the UI.

5. UI Design Using XAML

Now, let’s design the user interface using XAML. We will bind the UI with the ProductViewModel created earlier.

<Window x:Class="ProductApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Product List" Height="350" Width="525">
    <Window.DataContext>
        <local:ProductViewModel />
    </Window.DataContext>

    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="2*"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>

        <ListBox ItemsSource="{Binding Products}" 
                 SelectedItem="{Binding SelectedProduct}" 
                 DisplayMemberPath="Name" 
                 Margin="10" />

        <StackPanel Grid.Column="1" Margin="10">
            <TextBlock Text="Product Name:" FontWeight="Bold"/>
            <TextBlock Text="{Binding SelectedProduct.Name}" />

            <TextBlock Text="Price:" FontWeight="Bold"/>
            <TextBlock Text="{Binding SelectedProduct.Price, StringFormat={}{0:C}}" />

            <TextBlock Text="Description:" FontWeight="Bold"/>
            <TextBlock Text="{Binding SelectedProduct.Description}" TextWrapping="Wrap" />
        </StackPanel>

    </Grid>
</Window>

The above XAML code sets up a basic layout and uses a ListBox to display the product list. When a user selects a product from the ListBox, the details of the selected product are displayed in the right area.

6. Running the Application and Checking Results

Now that all the code has been written, let’s run the application to check the results. By pressing the F5 key to run it in debug mode, you will see the UI as shown below.

Product List Application

7. Conclusion

In this course, we created a simple product list and details application using WPF. By applying the MVVM pattern, we separated Model, View, and ViewModel, enhancing code readability and maintainability. We were able to easily implement the connection between the user interface and business logic by utilizing WPF’s data binding capabilities.
I hope this course has enhanced your understanding of fundamental data binding and MVVM in WPF.

Moving forward, I encourage you to develop more complex and diverse WPF applications. Utilize the various features of WPF to create even more appealing user interfaces!