Windows phone - 将列表绑定到LongListSelector

时间:2013-11-03 07:16:02

标签: c# windows xaml binding windows-phone-8

我是Windows Phone开发的新手,我一直在尝试将列表绑定到基础数据透视表应用程序中包含的LongListSelector,但没有成功。

这是主页面的构造函数(发生绑定的地方):

public MainPage()
        {
            InitializeComponent();
            List<int> testList = new List<int>();
            testList.Add(0);
            testList.Add(1);
            testList.Add(2);
            listDisplay.ItemsSource = testList;

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;

            // Sample code to localize the ApplicationBar
            //BuildLocalizedApplicationBar();
        }

这是LongListSelector的XAML:

<vm:MainViewModel
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:PivotApp2.ViewModels"
    SampleProperty="Sample Text Property Value">

    <vm:MainViewModel.Items>
        <vm:ItemViewModel x:Name="listModel" LineOne="{Binding Source}"/>
    </vm:MainViewModel.Items>

</vm:MainViewModel>

我在这里做错了什么,我怎样才能让绑定工作?

1 个答案:

答案 0 :(得分:2)

让我们从View-model开始,我们需要在这个类中进行数据绑定:

class ViewModel
    {
        private ObservableCollection<string> _strings = new ObservableCollection<string>();

        public ObservableCollection<string> Strings //It's our binding property
        {
            get
            {
                return _strings;
            }
            set
            {
                if (value==null)
                {
                    throw new NullReferenceException();
                }
                _strings = value;
            }
        }
    } 

在此代码中,我们使用ObservableCollectin,它表示动态数据集合,在添加,删除项目或刷新整个列表时提供通知。

然后我们需要添加一些数据:

public MainPage()
    {
        InitializeComponent();
        ViewModel tempViewModel = new ViewModel();
        var strings = new List<string> { "text1", "text2", "text3" };

        tempViewModel.Strings = new ObservableCollection<string>(strings);

        this.DataContext = tempViewModel;

    }

最后我们需要用视图来传达我们的视图模型:

<ListBox ItemsSource="{Binding Strings}"/>