Recently, when I was learning WPF binding, I didn't understand the role of DataContext, which often led to data binding problems.
1, WPF application has UI layer and data layer, which are connected through DataContext. It should be noted that the C# code of the View class, andNot the data layer.
2, UI objects without DataContext will inherit their data layer from their parent objects
Copy code
Copy code 3, two ways to specify DataContext for UI layer.One is in the View background:
var cont = new MainViewModle(); DataContext = cont; One is in XAML:
In WPF, an application has two layers: UI layer and Data layer.Create a new project here to explain which is the UI layer and which is the data layer The UI layer is obviously the interface that the user sees.But the data layer is not as shown below: onThe picture shows the background code of the UI layer view.Of course, you can use events to write all the business logic code here, but when we use MVVM, the business logic is decoupled from here, and the data layer is DataContext, which is not specified at this time. Next, we create a new directory, and then add a class file: Then specify the VM class as DataContext: Data context is used in data binding, and the DataContext property is the default source of binding, unless you specialDeclare another source.The DataContext property has no default source (null from the start), but since DataContext is inherited down through the control hierarchy, you can set a DataContext for the Window itself and then use it in all child controls.
UI XAML code:
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:WpfApp1"mc:Ignorable="d"Title="Test DataContext" Height="450" Width="800">Background binding:
public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();this.DataContext = this;}}The code-behind for this example just adds an interesting line of code: after the standard InitalizeComponent() call, we assign the "this" reference to the DataContext, which just tells the window that we want our ownbecome the data context.In XAML, we use this fact to bind to several Window properties, including Title, Width, and Height.Since the window has a DataContext, which is passed to the child controls, we don't have to define a source on each binding - we just use the values as if they were available globally.
Try running the example and resize the window - you will see the size change reflected in the text box immediately.You could also try writing a different title in the first textbox, but you might be surprised that this change isn't reflected right away.Instead, you must move focus to another control before applying the changes.