Chapter 9 Data Binding
Table of contents
9.1 Basic concepts of data binding
WPF provides three data binding technologies: Binding, MultiBinding, PriorityBinding
The base class of these three Bindings is BindingBase, and BindingBase inherits from MarkupExtension
In WPF, both ContentControl (such as Button) and ItemsControl (such as ListBox and ListView) provide built-in functions that enable flexible data binding of a single data item or a collection of data items, and can generate sorted, filtered, and grouped view
System.Windows.Data.Binding类:
Bind the additional property of **"target" with the property of data "source", which can be any property with public modifier
Binding syntax :
<object property="{Binding declaration}" .../>
//object为绑定目标;declaration为绑定声明,如果有多个绑定声明,各绑定声明之间用逗号分隔
<Slider Name="slide1" Maximum="100" />
<TextBlock Text="{Binding ElementName=slide1,Path=Value}" />
9.1.1 Bindings and binding expressions
Binding refers to binding a dependency property of the "target" to a CLR property of the "source"
BindingExpression is the basic object that maintains the connection between the binding source and the binding target . A Binding instance can contain multiple BindingExpression instances
9.1.2 Binding mode (Mode attribute)
1. OneWay: one-way binding
Features : When the source changes, the target also changes automatically, which is suitable for the case where the bound control is an implicit read-only control (such as the student number), or the target property does not have a control interface for changing (such as the background of the table color)
<TextBlock
Text="{Binding ElementName=listBox1,
Path=SelectedItem.Content, Mode=OneWay}"/>
2. TwoWay: two-way binding
Features : When one of the source or target changes, the other will also change automatically, suitable for editable or interactive UI schemes
<TextBox Text="{Binding ElementName=listBox2,
Path=SelectedItem.Content,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
3. OneTime: single binding
Features : The target is only updated when the application starts or the data context (DataContext) changes , after which the change of the source no longer affects the target, suitable for binding static data, it is essentially a simplified form of OneWay binding
<TextBox Text="{Binding ElementName=listBox3,
Path=SelectedItem.Content,
Mode=OneTime}" />
4. OneWayToSource: reverse binding
Features : When the target changes, the source also changes, which is just the opposite of OneWay binding
<TextBox Text="{Binding ElementName=listBox4,
Path=SelectedItem.Content,
Mode=OneWayToSource,
UpdateSourceTrigger=PropertyChanged}" />
5. Default: automatically obtain the default Mode value of the target attribute
If the binding mode is not declared, the default is Default. In general, editable control properties (such as properties of text boxes and check boxes) default to two-way binding, while most other properties default to one-way binding
<TextBox Text="{Binding ElementName=listBox2,
Path=SelectedItem.Content,
Mode=Default,
UpdateSourceTrigger=LostFocus}" />
9.1.3 Controlling when to update the source (UpdateSourceTrigger)
-
Explicit: The source is only updated when the UpdateSource method of BindingExpression is called with C# code
-
LostFocus: Automatically update the source when the target control loses focus
-
PropertyChanged: The source is automatically updated every time the bound property of the target control changes
<TextBox Text="{Binding ElementName=listBox2,
Path=SelectedItem.Content,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />
9.1.4 Binding path syntax (Path property)
(1) The value of Path is the attribute name of the source object (commonly used, examples in this chapter)
(2) Other cases of Path values:
(a) When binding to an attached property, you need to enclose it in parentheses
(b) Use square brackets to specify the property indexer, and you can also use nested indexers.
(c) Inside the indexer, you can use multiple indexer parameters separated by commas, and you can also use parentheses to specify the type of each parameter (d
) If the source is a collection view, you can use a slash (/) Specifies the current item
(e) can be bound to the current source using a dot (.) path
9.1.5 Data Conversion
When describing data bindings in XAML, WPF provides type converters that convert values of some types into string representations. However, in some cases, it may be necessary for the developer to customize the converter
For example, when the source object of the binding is a property of type DateTime, in this case, in order for the binding to work properly, the property value needs to be converted to a custom string representation first
To associate a converter with a binding, generally create a class that implements the IValueConverter interface, and then implement two methods: the Convert method and the ConvertBack method
9.2 Simple data binding
9.2.1 Specifying the binding source directly in a single property
ElementName: The source is another WPF element
<Slider Name="slide1" Width="100" Maximum="100" />
<Rectangle Width="{Binding ElementName=slide1,Path=Value}" Height="15" Fill="Red" />
Souce: The source is a CLR object
<Page …… xmlns:src="clr-namespace:ch11.Examples">
<TextBlock Text="{Binding XueHao,
Source={StaticResource info}}" />
Bind to a CLR object with Source
The Source attribute of the Binding class indicates that the bound data source is a CLR object, which can be an instance of a class provided by the .NET framework or an instance of a custom class
Binding relative targets with RelativeSource
RelativeSource: source and target are the same element
RelativeSource indicates that the "source" is itself. The RelativeSource property is useful when binding a property of an object to another property of itself, or when using data binding in styles (Style) or templates (ControlTemplate)
<Rectangle Width="100"
Height="{Binding RelativeSource={RelativeSource Self},
Path=Width}" />
9.2.2 Binding multiple properties to the same source via DataContext
(1) You only need to declare DataContext once on the parent element
(2) "Bingding Path=..." of each child element can be omitted as: "Bingding ..."
Chapter 10 Databases and the Entity Data Model
10.1 Create database and tables
10.1.1 ADO.NET data access technology
1. Use DataSet to access the database
This is a technology provided by ADO.NET when it was first launched, and it is used to process data in a disconnected mode. This technology uses DataSet residing in local memory as the middle layer, that is, the application program interacts with DataSet, DataSet Then interact with the database
2. Use LINQ to DataSet to access the database
In this way, the application can use the LINQ syntax to access the DataSet, which is more flexible and simpler than the first way
3. Use LINQ to SQL to access the database
This method directly interacts with the SQL Server database, with high execution efficiency and fast speed, but this method does not support other types of databases . In LINQ to SQL, first use the O/R designer to build the model, and then use the model to pass SQL Statements, execute SQL commands, and directly access SQL Server with LINQ syntax
When using this technology, it is generally used to design a custom middle-level object model (middleware), and then make it into a .dll file for other applications to call
4. Use EF and LINQ to Entities to access the database (recommended method)
This is the recommended database access method. This model can support various types of databases (including SQL Server, Oracle, DB2, MySQL, etc.), and the database access engine of this model can be directly provided by the database supplier.
10.1.2 Introduction to SQL Server 2014
Key features of the SQL Server 2014 database engine :
(1) Provides cross-cluster migration of AlwaysOn availability groups for operating system upgrades
(2) Enhancements for programmability
(3) Enhancements for scalability and performance
(4) Provides support for cloud computing and big data support
10.1.3 Create a LocalDB database
Introducing LocalDB : A service -based database, but only accessible locally
Pros : Easy to use, and no modifications are required to copy projects and databases from one computer to another
When accessing the LocalDB database through the application, VS2015 will automatically attach the .mdf file to the default instance of LocalDB . When the database is no longer used, LocalDB will automatically separate the .mdf file from the default instance .
The basic usage of creating a database directly in VS :
Method 1 : Select [Service-based database] to directly create a database (MyDb.mdf)
Method two :
(1) Select [ADO.NET Entity Data Model]
(2) Select [Code First from the database]
10.2 Creating an Entity Data Model with Entity Framework
10.2.1 Entity Framework Basic Concepts
Advantages of Entity Framework:
(1) Applications can work through a conceptual model including types with inheritance, complex members, and relationships (2) Applications no
longer have hard-coded dependencies on specific data engines or storage
Changing the mapping between the conceptual model and the storage-specific schema without changing the application code
(4) Developers can use consistent applications that map to various storage schemas (possibly implemented in different database management systems) Object model
(5) Multiple conceptual models can be mapped to the same storage architecture
10.2.2 Entity Framework Development Patterns
1. Database First
Create the database first, and then manually generate the corresponding entity data model (.edmx file) according to the database. If the database structure changes, the model must be manually generated again
2. Model First
First create an entity data model (.edmx file) using the template provided by the development tool, and then generate a database based on the entity data model
3. Code First (Code First, suggested technique)
[Actual] Write the data model class first , and then generate the database accordingly
[Reference] Create the database first, and then generate the entity data model class. This method is only used to generate reference code
If the article is helpful to you, remember to support it with one click and three links~