WPF development, code writing self-written

WPF (Windows Presentation Foundation) is a powerful UI framework used to develop Windows applications, as part of the .NET Framework. By leveraging WPF, it becomes easy to build complex user interfaces, offering a rich user experience through features such as data binding, animations, styles, and templates. In this article, we will start with the basics of WPF development and explain how to learn concepts through writing code and how to actually develop applications.

Basic Concepts of WPF

WPF uses XAML (eXtensible Application Markup Language) to define the UI and implements business logic using .NET languages like C# or VB.NET. The fundamental elements of WPF are as follows:

  • XAML (eXtensible Application Markup Language): A markup language used to define WPF UI.
  • Control: Elements such as Button, TextBox, and ListBox that enable interaction with the user.
  • Data Binding: Establishes a connection between UI elements and data sources, automatically reflecting changes in the UI.
  • Styles and Templates: Used to define and customize the appearance of UI elements.

Basics of XAML

XAML is used to design the UI of WPF applications, and the basic XAML file structure is as follows:

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Main Window" Height="350" Width="525">
    <Grid>
        <Button Name="myButton" Content="Click Me" Width="100" Height="30" Click="myButton_Click"/>
    </Grid>
</Window>

Description of UI Elements

In the above example, <Window> defines the main window of the application. <Grid> acts as a container for arranging the layout, which includes the <Button> element. The Name property of the button serves as an identifier for connecting events.

Writing Logic in C#

After defining the user interface of a WPF application, actual behaviors must be implemented in C#. Below is a method for handling the button click event.

using System.Windows;

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

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

Event Handling

The event handler myButton_Click is called when the user clicks the button. It displays a simple message using the MessageBox.Show method.

Understanding Data Binding

Utilizing data binding in WPF simplifies the connection between the view and the model. Below is an example that uses data binding.

<Window x:Class="MyApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Data Binding Example" Height="200" Width="400">
    <Grid>
        <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" Width="200"/>
        <TextBlock Text="{Binding Name}" Margin="0,30,0,0"/>
    </Grid>
</Window>

Data Model Class

To use data binding, a data model class must first be created. Below is a simple example of a model class.

using System.ComponentModel;

namespace MyApp
{
    public class Person : INotifyPropertyChanged
    {
        private string _name;

        public string Name
        {
            get { return _name; }
            set 
            {
                if (_name != value)
                {
                    _name = value;
                    OnPropertyChanged("Name");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

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

Understanding ViewModel and MVVM Pattern

In WPF, the MVVM (Model-View-ViewModel) pattern is used to structure applications. By utilizing the MVVM pattern, you can separate the UI from business logic, enhancing reusability and maintainability. The ViewModel class acts as an intermediary between the view and the model, updating the state of the view through data binding.

Example of ViewModel Class

namespace MyApp
{
    public class MainViewModel
    {
        public Person Person { get; set; }

        public MainViewModel()
        {
            Person = new Person { Name = "John Doe" };
        }
    }
}

Setting ViewModel Data Context in XAML

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
    }
}

Utilizing Styles and Templates

Styles and templates play an essential role in altering the design of WPF UI. Below is an example of applying a style to a button.

<Window.Resources>
    <Style TargetType="Button">
        <Setter Property="Background" Value="LightBlue"/>
        <Setter Property="Foreground" Value="White"/>
    </Style>
</Window.Resources>

Using Templates

Templates allow you to freely define the layout of UI elements. Below is an example that defines a ControlTemplate for a button.

<Button>
    <Button.Template>
        <ControlTemplate TargetType="Button">
            <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="2">
                <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
            </Border>
        </ControlTemplate>
    </Button.Template>
    Button Text
</Button>

Conclusion

In this post, we have explored the basic concepts of WPF development and how to write code. We learned to structure and design applications using XAML and C#, along with data binding, the MVVM pattern, styles, and templates. To develop an actual application, it’s essential to gradually build upon this foundation by adding more complex functionalities.

WPF is a framework with a broad scope that provides powerful data connectivity and user experience, going beyond simple UI development to create advanced applications. Continue to explore WPF’s various features and create your own projects!

Thank you.