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

zbdgwd5y  于 2021-06-17  发布在  Mysql
关注(0)|答案(2)|浏览(356)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

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

tjvv9vkg

tjvv9vkg1#

根据您的要求,我想建议您遵循mvvm,正如在评论中所建议的那样。以下是实现目标的步骤。
定义您的模型,其中包含所有必需的属性,如picture、id、title、description等。
定义viewmodel,其中包含模型的ObservaleBollection或list(根据您的需求)。
用你喜欢的任何orm从db填充你的集合。
您需要美化ui以显示项目列表。我建议您使用列表视图并定义(itemtemplate、itemcontainerstyle和itempanel)。
将listview与vm的属性(模型的集合)绑定。仅此而已
注意:每个项目中都有按钮。当您将itemsource设置为listview时,默认情况下,它将在相关模型中查找命令。如果您想为所有项按钮定义公共命令,您需要在vm中创建命令,并通过使用relativesource和finding祖先将此命令绑定到listview itemtemplate按钮,以便在祖先datacontext中搜索vm的命令。

50pmv0ei

50pmv0ei2#

定义产品型号:

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
    }
}

定义产品视图模型。它只是 Package 模型并提供“添加到购物车”命令:

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));
        }
    }
}

定义视图。你需要一个 ItemsControl , ItemTemplate 以及 WrapPanel :

<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>

结果:

样本项目在这里。

相关问题