Windows Presentation Foundation Introduction(IV) - Data Binding

30 篇文章 0 订阅
9 篇文章 0 订阅

/*by Jiangong SUN*/


In WPF, you can bind dependency properties to Managed Object, toADO.NET Data source, toXML Data and to UI Element

Data binding is the process that establishes a connection between two properties. It enables the data-binding engine to keep the properties synchronized, including converting types as appropriate.


Data binding provides a connection between a binding target and a binding source. 

Each binding has the following four components:
A binding target object.
A target property, which must be a dependency property.
A binding source.
A path to the value in the binding source to use.


Note: Most UIElement properties are dependency properties and most UIElement properties, except read-only properties, support data binding by default.


Data binding modes:
OneWay. This binding mode causes changes to the source property to update the target property, but changes to the target property are not synchronized back with the source property. This approach is appropriate for read-only data scenarios.
TwoWay. This binding mode causes changes to both the source property and the target property to be synchronized with each other. This approach is suitable for editable form scenarios.
OneWayToSource. This binding mode is the reverse of the OneWay binding mode. Changes to the target property update the source property, but changes to the source property do not update the target property. This approach is suitable for scenarios where you need to reevaluate the source value from the UI.
OneTime. This binding mode causes the source property to initialize the target property, but any subsequent changes to either source property or the target property are not synchronized. This approach is suitable for scenarios where you only require a snapshot of the data or the source data is static.


XPATH:
You use the XPath property of the Binding object to bind to XML data instead of a managed object. By setting the XPath property, you are creating an XML Path Language (XPath) query to select a node or collection of nodes. The result of an XPath query is a System.Xml.XmlNode, which is a managed object, so you can bind to its properties by using the Path property. XPath functions are not supported in the XPath property.
(reference:http://www.w3schools.com/xpath/xpath_syntax.asp)

For example:

<XmlDataProvider x:Key="inventoryData"
      Source="InventoryData.xml"
      XPath="Inventory/Books" />
 
      <TabItem Header="XML Data">
        <ListBox>
          <ListBox.ItemsSource>
            <Binding Source="{StaticResource inventoryData}"
                     XPath="*[@Stock='out'] | *[@Number>=8 or @Number=3]" />
          </ListBox.ItemsSource>
          <ListBox.ItemTemplate>
            <DataTemplate>
              <WrapPanel>
                <WrapPanel.ToolTip>
                  <TextBlock Text="{Binding XPath=Summary}" />
                  </WrapPanel.ToolTip>
                <TextBlock Text="{Binding XPath=Title}">
                </TextBlock>
                <TextBlock Text=" [" />
                <TextBlock Text="{Binding Path=Attributes[0].Value}" />
                <TextBlock Text="]" />
              </WrapPanel>
            </DataTemplate>
          </ListBox.ItemTemplate>
        </ListBox>
      </TabItem> 


Binding to a Class Property
Example:
class:
namespace MySample
{
  public class MyData
  {
    public MyData()
    {
      this.ColorName = "Red";
      this.Description = "Button background color";
      this.ForeColorName = "Blue";
    }


    public string ColorName { get; set; }
    public string Description { get; set; }
    public string ForeColorName { get; set; }
  }
}

declaration in xml: 
xmlns:c="clr-namespace:MySample"

definition source:
<c:MyData x:Key="myDataSource"/>

utilisation:
<Button Background="{Binding Path=ColorName, Source={StaticResource myDataSource}}">

TwoWay and OneWayToSource bindings listen for changes in the target property and propagate them back to the source. 
However, the time when the binding engine updates the source value depends on the value of the UpdateSourceTrigger, which can have one of the following values:
LostFocus. The binding engine updates the source value when the binding target loses focus.
PropertyChanged. The binding engine updates the source value when the target property changes.
Explicit. The binding engine updates the source value when the application calls the UpdateSource method.

The default value for the UpdateSourceTrigger property for most dependency properties is PropertyChanged, although the Text property has a default value of LostFocus.


How to implement Property Change Notifications:
1)Implementing Property Change Notifications by Using Dependency Properties
One way to implement property change notifications is to use dependency properties, which automatically provide change notification and provide additional benefits such as styling, animation, and space storage. You typically use dependency properties to implement property change notification in visual elements such as UI controls.

2)Implementing Property Change Notification by Using the INotifyPropertyChanged Interface
You typically use this approach to implement property change notifications for business objects.


To implement the INotifyPropertyChanged interface:
Declare the PropertyChanged event.
Create the OnPropertyChanged method to raise the event.
Call the OnPropertyChanged method for each property for which you want change notifications whenever the property is updated.


Data Conversions: 
The data types of the source and target properties in a data binding must be compatible. 
If the data types are not the same, data conversion occurs to convert between the two data types.

Data Validation:
Most applications that receive user input must have validation logic that ensures that the user has entered the expected information. The validation checks can be based on type, range, format, or some other application-specific requirements.
WPF enables you to implement validation logic for your applications by associating ValidationRules with your OneWay and OneWayToSource Binding objects.

Data Binding to Collections:
Binding to a data collection is a common scenario. Typically, you use an ItemsControl element such as ListBox, ListView, or TreeView to display a data collection. You use the ItemsSource property to bind an ItemsControl element to a data collection.
Note: The data binding to the ItemsSource property is OneWay because the ItemsSource property supports OneWay binding by default.

You can enumerate over any collection that implements the IEnumerable interface. However, to create dynamic bindings so that insertions or deletions in the collection update the UI, the collection must also implement the INotifyCollectionChangedInterface, which exposes an event that is raised when the underlying collection changes.

Binding to Observable  Collection 

Binding to ADO.NET Data Objects:
DataSet
DataTable
DataView


LINQ: Language INtegrated Query
LINQ extends the Microsoft .NET Framework to provide general-purpose query facilities that apply to all sources of information, not just relational or XML data. 


DataSet vs DataTable: DataSet is a set of DataTables


Collection views provide a layer on top of the binding source collection that enables you to navigate and display the source collection based on sort, filter, and group queries without manipulating the underlying source collection. If the source collection implements the INotifyCollectionChanged interface, the data-binding engine propagates the changes to the views when the collection raises the CollectionChanged event.


Collection view is not suitable for big data treatment


Hope this helps! Enjoy coding!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值