Skip to content

Commit

Permalink
Rewrite Framework databinding how-to
Browse files Browse the repository at this point in the history
  • Loading branch information
adegeo committed Jul 24, 2024
1 parent 6cbddf3 commit 3ae3f85
Show file tree
Hide file tree
Showing 10 changed files with 253 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -1,28 +1,79 @@
---
title: "How to: Create a Simple Binding"
title: "How to create a data binding"
description: Create a simple binding for your applications through this how-to example in Windows Presentation Foundation (WPF).
ms.date: "03/30/2017"
ms.date: 07/24/2024
helpviewer_keywords:
- "simple binding [WPF], creating"
- "data binding [WPF], creating simple bindings"
- "binding data [WPF], creating"
ms.assetid: 69b80f72-6259-44cb-8294-5bdcebca1e08
#customer intent: As a devleoper, I want to create a binding so that I can present information in a UI
---
# How to: Create a Simple Binding

This example shows you how to create a simple <xref:System.Windows.Data.Binding>.

## Example

In this example, you have a `Person` object with a string property named `PersonName`. The `Person` object is defined in the namespace called `SDKSample`.

The highlighted line that contains the `<src>` element in the following example instantiates the `Person` object with a `PersonName` property value of `Joe`. This is done in the `Resources` section and assigned an `x:Key`.

[!code-xaml[SimpleBinding](~/samples/snippets/csharp/VS_Snippets_Wpf/SimpleBinding/CSharp/Page1.xaml?highlight=9,37)]

The highlighted line that contains the `<TextBlock>` element then binds the <xref:System.Windows.Controls.TextBlock> control to the `PersonName` property. As a result, the <xref:System.Windows.Controls.TextBlock> appears with the value "Joe".

## See also

# How to create a data binding

This article describes how to create a binding XAML. The example uses a data object that represents an employee at a company. This data object is bound to a XAML window that uses `TextBlock` controls to list the employee's details.

To learn more about data binding, see [Data binding overview in WPF](data-binding-overview.md). To learn more about data binding, see [Data binding overview in WPF](data-binding-overview.md).

:::image type="content" source="media/how-to-create-a-simple-binding/preview.png" alt-text="A WPF window that shows details about an employee, such as their first name, last name, title, hire date, and salary.":::

## Create a data object

In this example, an employee is used as the data object that the UI is bound to.

1. Add a new class to your project and name it `Employee`.

Check failure on line 25 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Spaces after list markers [Expected: 1; Actual: 2]
1. Replace the code with the following snippet:

Check failure on line 26 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Spaces after list markers [Expected: 1; Actual: 2]

:::code language="csharp" source="./snippets/how-to-create-a-simple-binding/csharp/Employee.cs":::

The employee data object is a simple class that describes an employee:

- First and last name.
- Hire date.
- Title.
- Monthly income.

## Bind to a data object

The following XAML demonstrates using the `Employee` class as a data object. The root element's `DataContext` property is bound to a static resource declared in the XAML. The individual controls are bound to the properties of the `Employee`.

1. Add a new **Window** to the project and name it `EmployeeView`

Check failure on line 41 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Spaces after list markers [Expected: 1; Actual: 2]
1. Replace the XAML with the following snippet:

Check failure on line 42 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Spaces after list markers [Expected: 1; Actual: 2]

> [!IMPORTANT]
> The following snippet is taken from a C# project. If you're using Visual Basic, the `x:Class` should be declared without the `ArticleSample` namespace. You can see what the Visual Basic version looks like [here]().

Check failure on line 45 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

No empty links [Context: "[here]()"]

Check failure on line 46 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Trailing spaces [Expected: 0 or 2; Actual: 4]
:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" highlight="7-9,33-37,43":::

Check failure on line 48 in dotnet-desktop-guide/framework/wpf/data/how-to-create-a-simple-binding.md

View workflow job for this annotation

GitHub Actions / lint

Trailing spaces [Expected: 0 or 2; Actual: 4]
The namespace of the code won't match your project's namespace, unless you created a project named **ArticleSample**. You can copy and paste the `Window.Resources` and root element (`StackPanel`) into you're **MainWindow** if you created a new project.

Here are some important aspects about the XAML code:

- A XAML resource is used to create an instance of the `Employee` class.

Typically the data object is passed to or associated with the Window. This example hardcodes the employee for demonstration purposes.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="6-10":::

- The root element (`StackPanel`) has its data context set to the hardcoded `Employee` instance.

The child elements inherit their `DataContext` from the parent, unless explicitly set.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="11":::

- The properties of the `Employee` instance are bound to the `TextBlock` controls.

The `Binding` doesn't specify a `BindingSource`, so the `DataContext` is used as the source.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="33-37":::

- A `TextBox` control is bound with `TwoWay` mode, allowing the `TextBox` to change the `Employee.Salary` property.

:::code language="xaml" source="./snippets/how-to-create-a-simple-binding/csharp/EmployeeView.xaml" range="43":::

## Related content

- [Data Binding Overview](data-binding-overview.md)
- [How to: Create a Binding in Code](how-to-create-a-binding-in-code.md)
- [How-to Topics](data-binding-how-to-topics.md)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Application x:Class="ArticleSample.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
StartupUri="MainWindow.xaml">
<Application.Resources>

</Application.Resources>
</Application>
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.ComponentModel;

namespace ArticleSample
{
public class Employee : INotifyPropertyChanged
{
private decimal _salary;
public event PropertyChangedEventHandler PropertyChanged;

public string FirstName { get; set; }
public string LastName { get; set; }
public string Title { get; set; }
public DateTime HireDate { get; set; }

public decimal Salary
{
get => _salary;
set
{
_salary = value;

// Support TwoWay binding
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Salary)));
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<Window x:Class="ArticleSample.EmployeeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ArticleSample"
Title="" Height="250" Width="300">
<Window.Resources>
<local:Employee x:Key="EmployeeExample" FirstName="Niki" LastName="Demetriou"
HireDate="2022-02-16" Salary="5012.00"
Title="Content Artist" />
</Window.Resources>
<StackPanel DataContext="{StaticResource EmployeeExample}">
<Label FontSize="32">Employee</Label>
<Border BorderBrush="Gray" BorderThickness="2" />
<Grid Grid.Row="1" Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<TextBlock Text="First Name:" Grid.Row="0" Margin="0,0,10,0" />
<TextBlock Text="Last Name:" Grid.Row="1" />
<TextBlock Text="Title:" Grid.Row="2" />
<TextBlock Text="Hire Date:" Grid.Row="3" />
<TextBlock Text="Salary" Grid.Row="4" />

<TextBlock Text="{Binding FirstName}" Grid.Row="0" Grid.Column="1" />
<TextBlock Text="{Binding LastName}" Grid.Row="1" Grid.Column="1" />
<TextBlock Text="{Binding Title}" Grid.Row="2" Grid.Column="1" />
<TextBlock Text="{Binding HireDate, StringFormat=d}" Grid.Row="3" Grid.Column="1" />
<TextBlock Text="{Binding Salary, StringFormat=C0}" Grid.Row="4" Grid.Column="1" />
</Grid>
<Border BorderBrush="Gray" BorderThickness="2" />

<StackPanel Margin="5,10" Orientation="Horizontal">
<TextBlock Text="Change Salary:" Margin="0,0,10,0" />
<TextBox Text="{Binding Salary, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, StringFormat=C0}" Width="100" />
</StackPanel>
</StackPanel>
</Window>
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for EmployeeView.xaml
/// </summary>
public partial class EmployeeView : Window
{
public EmployeeView()
{
InitializeComponent();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Window x:Class="ArticleSample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ArticleSample"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<StackPanel Margin="5">
<Button x:Name="Employee" Content="Employee" Margin="5" Click="Employee_Click" />
</StackPanel>
</Window>
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ArticleSample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Employee_Click(object sender, RoutedEventArgs e)
{
EmployeeView window = new EmployeeView();
window.ShowDialog();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>netframework4.8.1</TargetFramework>
<UseWpf>true</UseWpf>
<LangVersion>8.0</LangVersion>
<RootNamespace>ArticleSample</RootNamespace>
</PropertyGroup>

</Project>

0 comments on commit 3ae3f85

Please sign in to comment.