数据绑定如何工作

数据绑定如何工作

本文介绍了数据绑定如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据添加到列表框中。如果你看看我的XAML,这是我建立的listBox:

I'm in the process now of trying to add data into a listBox. If you look at my XAML this is my listBox that I have constructed:

<ListBox
            Height="517"
            HorizontalAlignment="Left"
            Margin="12,84,0,0"
            Name="searchList"
            VerticalAlignment="Top"
            Width="438"
            SelectionChanged="SearchList_SelectedEvent">

            <!-- What each listbox item will look like -->
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding firstName}" FontSize="28" />
                        <TextBlock Text="{Binding lastName}" FontSize="28" />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>

</ListBox>

在与包含listBox的屏幕相关联的.css类中:

And in my .css class that is associated with the screen containing the listBox:

public Search()
    {
        InitializeComponent();

        //The variables that I want to render in the list
        string firstName = "John";
        string lastName = "Smith";
    }

所以我的问题是,数据绑定是如何工作的?你可以看到,在XAML我试图绑定变量,但我不知道这是否会工作,或者我正在做的正确吗?

So my question is, how exactly does data binding work? You can see that in the XAML I've attempted to Bind the variables but I have no clue whether that will work or if I'm doing it correctly?

对于初学者,XAML如何知道在哪里找到这些变量?

For starters, how does the XAML know where to find those variables??

推荐答案

我建议你通过由Tomas Jansson在另一个答案中提出。
除了你的代码之外,

I suggest you go through this tutorial suggested by Tomas Jansson in another answer.Apart from that in your code,

首先你需要创建一个List或ObservableCollection,它包含可以绑定到ListBox的数据。 >

First you need to create a List or ObservableCollection which contains the data, which is bindable to the ListBox.

List myList = new List()
          {new Name() { firstName = "sdfjsdk", lastName= "sdfsfsjdf"},
           new Name() { firstName = "bthbbh", lastName= "ereyyyu"},
           new Name() { firstName = "svbfbb", lastName= "sdfertbn"} };

其中Name是

class Name()
{
    string firstName;
    string lastName;
}

然后在代码后面,

myList.ItemsSource = myList; //this lets the XAML from where to fetch the data to bind

这篇关于数据绑定如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:55