WPF Data Binding 2

Source: Internet
Author: User

You can itemssource the dependency property of a ItemsControl class control as a binding object for a collection. Then, if the set implements the generic interface of observablecollection<t>, it will be able to respond to changes in the interface as the collection changes.

ItemsSource = "{Binding}"                                    <!-->ItemsSource = {Binding Source = { StaticResource xxxx}}       <--the second way to use resources to display data XXXX!--> 
<x:key= "Persons"></local:persons>
DataContext = "{StaticResource Persons}" use control in the background if you are not using resources as data. DataContext = ... Such an expression to define DataContext
This statement after <--is the assignment of the parent control's DataContext property to the resource!-->

DataContext Shared Feeds

If many of the elements in the interface are bound to the same source object, only different properties. For this reason, WPF can specify an implicit data source without displaying the markup for each source,elementname,relativesource.

You can find a common parent element and specify the data context for it. Set his DataContext property. Then when the interface is displayed, if the binding does not have an explicit source object. WPF traverses the logical tree until it finds a non-empty datacontext.

1 <StackPanelDataContext="{Binding Source={staticresource Persons}}">2         <TextBlockText="{Binding Path=count}"></TextBlock>3         <ButtonWidth= "+"Click= "Button_Click">Add</Button>4         <ListBoxIsSynchronizedWithCurrentItem= "True"ItemsSource="{Binding}">5             <listbox.itemtemplate>6                 <DataTemplate>7                     <StackPanel>8                         <TextBlockText="{Binding Path=name}"></TextBlock>9                         <ImageWidth= "Max"Height= "Max"Source= "F:\Loose XAML photogallery\creek.jpg"></Image>Ten                     </StackPanel> One                 </DataTemplate> A             </listbox.itemtemplate> -         </ListBox> -</StackPanel>

Can be used in such a way. Also, you can use name if you want to avoid defining the data source as a resource. DataContext = ..... Such a way.

Rendering of data

We can display the data in the way we want, and in order to achieve this we can use two ways, one is to use the data template, and the other is to use a data converter.

1. Use the data template:

Many WPF control properties can be added to a data template, and the ContentTemplate property of the ContentControl control can control the rendering of content. Itemcontrol's ItemTemplate will be applied to every item. Headercontentcontrol has a HeaderTemplate property to control the rendering of the header, and so on.

5<listbox.itemtemplate>6<DataTemplate>7<StackPanel>8<TextBlockText="{Binding Path=name}"></TextBlock>9<ImageWidth= "Max"Height= "Max"Source= "F:\Loose XAML photogallery\creek.jpg"></Image>Ten</StackPanel> One</DataTemplate> A</listbox.itemtemplate>

Just one way to set up the data template.

Of course datatemplate do not need to be declared by the inline, they are usually treated as a resource. As a result, they can be shared across multiple elements, allowing the Datatemmplate object to be automatically applied to the specified attribute, regardless of the attribute. This can be achieved by setting the DataType property to a specific type.

        <DataTemplateDataType= "Local:person"x:key= "Persontemplate">            <StackPanel>                <TextBlockText="{Binding Path=name}"></TextBlock>                <ImageWidth= "Max"Height= "Max"Source= "F:\Loose XAML photogallery\creek.jpg"></Image>            </StackPanel>        </DataTemplate>
        <issynchronizedwithcurrentitem= "True"  ItemsSource= "{ Binding}"  ItemTemplate="{StaticResource resourcekey=persontemplate} " >        </ ListBox >

2. Value Converter

A value converter can convert a source value to a completely different target value. They can be used to insert custom logic, but do not abandon the benefits of data binding. The purpose of a value converter is to achieve a conversion between the source and target data types. In fact, the use of value converters is divided into two cases of 1. The original and target values are compatible types, just want to modify the data to be displayed. 2. The original value and the target value are incompatible, and the value converter is implemented to display the original value.

        <x:key= "Backgroundconverter"></local:backgroundconverter  >   <  defining!--in Resources>
<x:name
Background =" {Binding Elementname=picturebox,path=items.count,converter={staticresource resourcekey=backgroundconverter}, Converterparameter=lightblue}">
</TextBlock>

Shown above is how the value converter is used, the definition of the value converter is to implement IValueConverter this interface

1      Public classShowtextconverter:ivalueconverter2     {3 4          Public ObjectConvert (ObjectValue, Type TargetType,Objectparameter, System.Globalization.CultureInfo culture)5         {6             stringShowstr ="number of pictures under current folder:";7             intnum =int. Parse (value. ToString ());8             return(num = =1|| num = =0) ? Showstr + Num. ToString () +"Item": Showstr + num. ToString () +"Items"; 9         }Ten  One          Public ObjectConvertback (ObjectValue, Type TargetType,Objectparameter, System.Globalization.CultureInfo culture) A         { -             Throw Newnotimplementedexception (); -         } the}
View Code

Value to convert
TargetType the type to be converted to
parameter is set to NULL by default,
Culture uses U.S. English as the default, en-us, although such a binding can control both values through Binding.converterparameter and binding.converterculture.

Note that the converterparameter=lightblue statement is in the XAML statement above. By default, paramter is set to NULL, but use this sentence to pass the parameter parameter to the conversion method.

Another case of using a value converter is that the source and destination are compatible, but you want to customize the display as appropriate

1      Public classShowtextconverter:ivalueconverter2     {3 4          Public ObjectConvert (ObjectValue, Type TargetType,Objectparameter, System.Globalization.CultureInfo culture)5         {6             stringShowstr ="number of pictures under current folder:";7             intnum =int. Parse (value. ToString ());8             return(num = =1|| num = =0) ? Showstr + Num. ToString () +"Item": Showstr + num. ToString () +"Items"; 9         }Ten  One          Public ObjectConvertback (ObjectValue, Type TargetType,Objectparameter, System.Globalization.CultureInfo culture) A         { -             Throw Newnotimplementedexception (); -         } the}
View Code

WPF Data Binding 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.