有没有办法在c#wpf中循环元素并将它们连接到MySQL数据库?

有没有办法在c#wpf中循环元素并将它们连接到MySQL数据库?,c#,mysql,database,wpf,loops,C#,Mysql,Database,Wpf,Loops,我正在用c#制作一个类似于网店的网站。所以我有了这个UI(见图),我想用一个循环(更少的代码)将数据绑定到UI元素。我可以用很多代码来编写这本手册,但这不是我想要的。我在考虑元素循环,但我找不到任何关于它的东西。 有人知道怎么做吗? 根据您的要求,我建议您遵循MVVM,评论中也有建议。以下是实现目标的步骤 定义模型,该模型包含所有必需的属性,如图片、ID、标题、说明等 定义ViewModel,其中包含模型的观测值集合或列表(根据您的需求) 用你喜欢的任何ORM从DB填充你的集合 您需要美化UI以

我正在用c#制作一个类似于网店的网站。所以我有了这个UI(见图),我想用一个循环(更少的代码)将数据绑定到UI元素。我可以用很多代码来编写这本手册,但这不是我想要的。我在考虑元素循环,但我找不到任何关于它的东西。 有人知道怎么做吗?

根据您的要求,我建议您遵循MVVM,评论中也有建议。以下是实现目标的步骤

  • 定义模型,该模型包含所有必需的属性,如图片、ID、标题、说明等
  • 定义ViewModel,其中包含模型的观测值集合或列表(根据您的需求)
  • 用你喜欢的任何ORM从DB填充你的集合
  • 您需要美化UI以显示项目列表。我建议您使用列表视图和定义(ItemTemplate、ItemContainerStyle和ItemPanel)
  • 将listview与VM的属性(模型的集合)绑定。 就这些

  • 注意:在每个项目中都有按钮。当您将items source设置为listview时,默认情况下它将在相关模型中查看命令。如果要为“所有项目”按钮定义公共命令,则需要在VM中创建命令,并使用RelativeSource和查找祖先将此命令绑定到listview itemtemplate按钮,以便在祖先数据上下文中搜索VM的命令。

    定义产品型号:

    public sealed class Product
    {
        public string Name { get; set; }
    
        public string Description { get; set; }
    
        public byte[] Image { get; set; }
    }
    
    定义从数据库加载产品的服务:

    public sealed class ProductsService
    {
        public async Task<IEnumerable<Product>> LoadProductsAsync()
        {
            // TODO: to load products from database use your favorite ORM
            // or raw ADO .NET; anyway, you want this to be async
            // since this is I/O bound operation
        }
    }
    
    结果:


    示例项目是。

    因为这个问题中没有代码或xaml,我猜您需要建议。我的建议是,不要害怕编写代码,使用MVVM模式并以最常见的方式绑定。在这个过程中,这将为您提供最丰富的体验和灵活的应用程序,未来的更改将更容易“我想用循环将数据绑定到UI元素”,您甚至不需要循环。只需使用
    ItemsControl
    基本上,您的图片看起来像
    ListBox
    +
    WrapPanel
    +
    itemstemplate
    。但它所说的问题太宽泛了。
    public sealed class ProductVm : ViewModelBase
    {
        private readonly Product model;
        private readonly Lazy<ImageSource> image;
    
        public ProductVm(Product model)
        {
            this.model = model;
    
            // we need to load image just once, hence here comes Lazy<T>
            image = new Lazy<ImageSource>(LoadImage);
    
            // TODO: add command initialization here;
            // usually you want DelegateCommand/RelayCommand/etc
            // AddToCartCommand = new DelegateCommand(AddToCart);
        }
    
        public string Name => model.Name;
    
        public string Description => model.Description;
    
        public ImageSource Image => image.Value;
    
        public ICommand AddToCartCommand { get; }
    
        private ImageSource LoadImage()
        {
            if (model.Image == null)
            {
                return null;
            }
    
            var image = new BitmapImage();
    
            using (var mem = new MemoryStream(model.Image))
            {
                image.BeginInit();
                image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = null;
                image.StreamSource = mem;
                image.EndInit();
            }
    
            image.Freeze();
    
            return image;
        }
    }
    
    public sealed class MainWindowVm
    {
        private readonly ProductsService productsService;
        private ObservableCollection<ProductVm> products;
    
        public MainWindowVm()
        {
            // in production apps, services must be injected using DI-containers
            // like Autofac, MEF, NInject, etc
            productsService = new ProductsService();
        }
    
        public IEnumerable<ProductVm> Products
        {
            get
            {
                if (products == null)
                {
                    // when UI wants to display products,
                    // we create empty collection and initiate async operation;
                    // later, when async operation will be finished,
                    // we will populate collection using values from database
                    products = new ObservableCollection<ProductVm>();
    
                    var _ = LoadProductsAsync();
                }
    
                return products;
            }
        }
    
        private async Task LoadProductsAsync()
        {
            // service returns collection of product models,
            // but we need collection of product view models
            var productModels = await productsService.LoadProductsAsync();
    
            foreach (var model in productModels)
            {
                products.Add(new ProductVm(model));
            }
        }
    }
    
    <Window x:Class="WpfApp3.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfApp3"
            mc:Ignorable="d"
            Title="MainWindow" Height="450" Width="800">
    
        <Window.DataContext>
            <local:MainWindowVm />
        </Window.DataContext>
    
        <ItemsControl ItemsSource="{Binding Products}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Vertical"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
    
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type local:ProductVm}">
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>
    
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition />
                            <ColumnDefinition />
                        </Grid.ColumnDefinitions>
    
                        <Image Grid.Row="0" Grid.Column="0" Grid.RowSpan="3" Width="48" Height="48" Source="{Binding Image}"/>
    
                        <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Name}"/>
                        <TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Description}"/>
                        <Button Grid.Row="2" Grid.Column="1" Content="Add to cart" HorizontalAlignment="Right" Command="{Binding AddToCartCommand}"/>
                    </Grid>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </Window>