简体   繁体   中英

WPF, Datatemplates, and Data binding

Not a specific code question of any sort, I'm just looking to better understand exactly how data binding works in a DataTemplate . Here's just an example block of code; I have defined a Client class with three attributes (the purpose of these attributes is irrelevant to the question)

public class Client
{
    public bool Powered { get; set; }
    public bool clientAlive { get; set; }
    public bool updaterAlive { get; set; }
}

I populate a ListView using a list of clients:

List<Client> clientList = new List<Client>();
//populate the list from JSON url, code omitted
listView1.ItemsSource = clientList;

And here's the block of XAML code that holds the template for displaying the items in the ListView:

<ListView.ItemTemplate>
    <DataTemplate>
         <WrapPanel>
             <TextBlock Text="Powered: " FontWeight="Bold" />
             <TextBlock Text="{Binding Powered}" />
             <TextBlock Text=", " />
             <TextBlock Text="clientAlive: " FontWeight="Bold" />
             <TextBlock Text="{Binding clientAlive}" />
             <TextBlock Text=", " />
             <TextBlock Text="updaterAlive: " FontWeight="Bold" />
             <TextBlock Text="{Binding updaterAlive}" />
         </WrapPanel>
    </DataTemplate>
</ListView.ItemTemplate>

The code runs fine and everything displays as expected, I was just wondering if anyone could explain how data binding in WPF works. As far as I'm concerned, there's nothing in the XAML that references the Client class and I'm just confused as to how the XAML knows to display the property the binding specifies. Does the Text = "{Binding = Powered}" just look for an attribute that matches the binding within the item type that populates the list?

Does the Text = "{Binding = Powered}" just look for an attribute that matches the binding within the item type that populates the list?

Basically, yes. If the item that your populated the list with didn't have that attribute, you would see binding errors (look in the console while debugging).

You can also supply a type to your DataTemplate which will allow you to have multiple templates that will be applied depending on the specific type of the object in your collection.

When the collection get bound to the listview, each list item container will be generated with Content set to Client object. So the visual present inside the data template has Client object as its data context.

The line "{Binding Powered}" will look up the datacontext and find the property named "Powered" and resolve its value. Just remove the word "Powered" and leave it as "{Binding}", WPF will display the fully qualified name of your datacontext object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM