【问题标题】:Windows phone - binding a list to a LongListSelectorWindows phone - 将列表绑定到 LongListSelector
【发布时间】:2013-11-14 01:36:33
【问题描述】:

我是 Windows Phone 开发的新手,我一直在尝试将列表绑定到基础 Pivot 应用程序中包含的 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>

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

【问题讨论】:

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


    【解决方案1】:

    让我们从 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}"/>
    

    【讨论】:

    • 多列列表如何实现
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    相关资源
    最近更新 更多