数据绑定列表到列表框C#XAML(Azure移动服务)UWP [英] Data Binding list to listbox C# XAML (Azure mobile services) UWP

查看:49
本文介绍了数据绑定列表到列表框C#XAML(Azure移动服务)UWP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个在线数据库.我希望查询结果显示在列表框中.我尝试使用数据绑定,但我认为这样做完全错误.

So I have an online database. And I want the query results to be displayed in a listbox. I tried to use data binding but I think I'm doing it totally wrong.

文件

[![在此处输入图片描述] [1]] [1]

[![enter image description here][1]][1]

class ProductTable
    {
        public string id { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public string Type { get; set; }
        public string Seller { get; set; }
        public int Expiration { get; set; }
    }

MainViewModel.cs

MainViewModel.cs

namespace Test
{
    class MainViewModel
    {
        IMobileServiceTable<ProductTable> product = App.MobileService.GetTable<ProductTable>();

        //In this method, load your data into Products
        public async void Load()
        {
            // This query filters out completed TodoItems.
            MobileServiceCollection<ProductTable, ProductTable> Products = await product
                .Where(ProductTable => ProductTable.Price == 15)
                .ToCollectionAsync();

            // itemsControl is an IEnumerable that could be bound to a UI list control
            IEnumerable itemsControl = Products;
        }
    }
}

XAML

    <Page x:Name="PAGE"
xmlns:local="clr-namespace:Test;assembly=Version1">
        <Grid>
            <Grid.DataContext>
                <local:MainViewModel />
            </Grid.DataContext>
            <ListBox Margin="10,10,10,100" x:Name="lb" ItemsSource="{Binding Products}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel>
                            <TextBlock Text="{Binding Name}" FontSize="10"></TextBlock>
                            <TextBlock Text="{Binding Title}" FontSize="10"></TextBlock>
                            <TextBlock Text="{Binding Description}" FontSize="10"></TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Page>

解决方案

表需要显式声明的JSON属性名称,否则您将无法使用数据绑定.

Table needs JSON property name explicitly declared otherwise you won't be able to use data binding.

Table.cs

public class ProductTable
{
    [JsonProperty(PropertyName = "id")]
    public string id { get; set; }

    [JsonProperty(PropertyName = "Name")]
    public string Name { get; set; }

    [JsonProperty(PropertyName = "Title")]
    public string Title { get; set; }

    [JsonProperty(PropertyName = "Description")]
    public string Description { get; set; }

    [JsonProperty(PropertyName = "Price")]
    public double Price { get; set; }

    [JsonProperty(PropertyName = "Type")]
    public string Type { get; set; }

    [JsonProperty(PropertyName = "Seller")]
    public string Seller { get; set; }

    [JsonProperty(PropertyName = "Expiration")]
    public int Expiration { get; set; }
}

XAML.cs 您无需声明新的列表框,只需使用itemsource.

XAML.cs You don't need to declare a new listbox, only use itemsource.

private async void button1_Click(object sender, RoutedEventArgs e)
{
    IMobileServiceTable<ProductTable> productTest = App.MobileService.GetTable<ProductTable>();

    // This query filters out completed TodoItems.
    MobileServiceCollection<ProductTable, ProductTable> products = await productTest
        .Where(ProductTable => ProductTable.Type == "Test")
        .ToCollectionAsync();

    lb.ItemsSource = products;

}

XAML

在面板中,切勿使用高度"*",这将导致严重错误!

<ListBox x:Name="lb" Margin="10,10,10,100" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Width="300">
                <TextBlock Text="{Binding Name}"  FontSize="10"></TextBlock>
                <TextBlock Text="{Binding Title}" FontSize="10"></TextBlock>
                <TextBlock Text="{Binding Description}" FontSize="10"></TextBlock>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

推荐答案

您正在创建两个ListBox-一个未显示的代码,另一个在XAML中绑定到任何DataContext.

You are creating two ListBoxes - one in code that isn't being displayed and one in XAML which is bound to whatever your DataContext is.

删除代码中的最后两行,并将XAML更改为:

Remove the last two lines in your code, and change your XAML to:

ItemsSource="{Binding Products}"

接下来,将产品"作为类的属性公开(如果要使用MVVM,则为ViewModel),并确保将ListBox的DataContext设置为所述ViewModel/class.

Next, expose Products as a Property on a class (ViewModel if you want to use MVVM), and ensure that the DataContext of your ListBox is set to said ViewModel/class.

我对MobileServiceCollection不熟悉,因此我认为它是可绑定的.如果不是,则将Products作为ObservableCollection(如果其中的值随时间而变化)或任何其他受支持的集合类型公开.

I'm not familiar with MobileServiceCollection, so I assume it is bindable. If it is not, expose Products as a ObservableCollection (if the values in it change over time), or any other supported collection type.

属性详细说明

创建一个类:

public class MainViewModel {
    //This is a property
    public ObservableCollection<ProductTable> Products { get; set; }

    //In this method, load your data into Products
    public void Load(){ 
        //Products = xxx
    }
}

在您的XAML中:

<Page [...]
    xmlns:local="clr-namespace:YourNamespace;assembly=YourProjectName">
    <Grid>
        <Grid.DataContext>
            <local:MainViewModel />
        </Grid.DataContext>
        <!-- ListBox goes in here somewhere, still with ItemsSource bound to Products -->
    </Grid>
</Page>

此处上了解更多有关命名空间的信息. >.

Read more about namespaces here.

这样做,您的Windows的DataContext将被设置为MainViewModel(也可以命名为ProductsViewModel).由于列表框将位于窗口内,因此它将继承(由于

By doing this, your Windows' DataContext will be set to the MainViewModel (could also be named ProductsViewModel). Since your ListBox will be within your Window, it will inherit (due to Property Value Inheritance) the same DataContext.

Binding将在ViewModel上查找属性产品".

The Binding will look for a property 'Products' on the ViewModel.

您将需要在某处调用Load()方法.

You will need to call the Load() method somewhere.

第2部分-查看代码后

请记住,我无法运行代码,所以我有点盲目.

Mind you, I am not able to run the code, so I'm flying somewhat blind.

Buy.xaml.cs

Buy.xaml.cs

public sealed partial class Buy : Page
{
    private readonly MainViewModel _viewModel;

    public Buy()
    {
        this.InitializeComponent();

        _viewModel = new MainViewModel();
        DataContext = _viewModel;
    }

    private async void button1_Click(object sender, RoutedEventArgs e)
    {
        _viewModel.Load();
    }
}

MainViewModel.cs

MainViewModel.cs

public class MainViewModel : INotifyPropertyChanged
{
    IMobileServiceTable<ProductTable> product = App.MobileService.GetTable<ProductTable>();

    public List<ProductTable> Products { get; private set; }

    public event PropertyChangedEventHandler PropertyChanged;

    public async void Load()
    {
        Products = await product
            .Where(ProductTable => ProductTable.Price == 15)
            .ToListAsync();

        //Notify that the property has changed to alert to UI to update.
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Products)));
    }
}

您需要将ProductTable公开,否则会出现编译错误.

You need to make ProductTable public, or you will get a compilation error.

希望上述内容使您能够使用上述的ItemsSource绑定来绑定ListBox.

Hopefully, the above will enable you to bind your ListBox using the ItemsSource binding described above.

请注意,上面的代码不一定是最佳实践.

And please note that the above code is not necessarily best practice.

这篇关于数据绑定列表到列表框C#XAML(Azure移动服务)UWP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆