简体   繁体   English

有没有办法在 Xamarin 中轻松地将网格绑定到表格,就像在我的 WinForms 代码中一样?

[英]Is there a way to easly bind a grid to a table in Xamarin, like in my WinForms code?

i am new to xamarin, i need to easily link a grid (or something similar) to my MySql database table.我是 xamarin 的新手,我需要轻松地将网格(或类似的东西)链接到我的 MySql 数据库表。 In WinForms I had done it by putting a grid with the designer and with a few lines of code, but instead with Xamarin I can't do anything ... My current project is a XamarinForm with the default "tab" preset.在 WinForms 中,我通过在设计器和几行代码中放置一个网格来完成它,但是使用 Xamarin 我不能做任何事情......我当前的项目是一个带有默认“选项卡”预设的 XamarinForm。

Here is the WinForm code:这是 WinForm 代码:

        try
        {
            MySqlConnection cnn;
            string connetionString = "server=sql7.freesqldatabase.com;database=------;port=----;uid=-------;pwd=------;";
            cnn = new MySqlConnection(connetionString);

            DataTable dt = new DataTable();

            MySqlCommand cmd;
            cnn.Open();

            cmd = cnn.CreateCommand();
            cmd.CommandText = "SELECT * from Products";
            MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
            adapter.Fill(dt);
            dataGridView1.DataSource = dt; //dataGridView WinFrom component

            cnn.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

Is there a way to do this in Xamarin?有没有办法在 Xamarin 中做到这一点? (my goal is to display all the db table in one page) (我的目标是在一页中显示所有数据库表)

Welcome to SO!欢迎来到 SO!

Although there is not the same way that Xamarin can use DataTable as Source directly, but there is an another way to convert Table Date and make it used for Control(Such as CollectionView , DataGrid , etc).虽然Xamarin可以直接使用DataTable作为 Source 的方式不一样,但是还有另一种方法可以转换 Table Date 并将其用于 Control(例如CollectionViewDataGrid等)。

For example, ItemSource can be set as follows:例如,ItemSource 可以设置如下:

MyDataGrid.ItemsSource = await TodoItemDatabase.Database.Table<TodoItem>().ToListAsync();

Here the TodoItem is the Model of table data, you need to create it in Xamarin Forms manually.这里的TodoItem是表数据的 Model,需要在 Xamarin Forms 中手动创建。 Then the app will convert the table data to list data according to the model style.然后应用程序会根据模型样式将表格数据转换为列表数据。

using SQLite;
public class TodoItem
{
    [PrimaryKey, AutoIncrement]
    public int ID { get; set; }
    public string Name { get; set; }
    public string Notes { get; set; }
    public bool Done { get; set; }
}

About using Databases in Xamarin, you can refer to this official document .And there is a sample project for reference.关于在Xamarin中使用Databases ,可以参考这个官方文档。并且有一个示例项目供参考。 Above code TodoItemDatabase class also based on this sample.以上代码TodoItemDatabase类也基于此示例。

Here is the TodoItemDatabase class:这是TodoItemDatabase类:

public class TodoItemDatabase
{
    static readonly Lazy<SQLiteAsyncConnection> lazyInitializer = new Lazy<SQLiteAsyncConnection>(() =>
    {
        return new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags);
    });

    public static SQLiteAsyncConnection Database => lazyInitializer.Value;
    static bool initialized = false;

    public TodoItemDatabase()
    {
        InitializeAsync().SafeFireAndForget(false);
    }

    async Task InitializeAsync()
    {
        if (!initialized)
        {
            if (!Database.TableMappings.Any(m => m.MappedType.Name == typeof(TodoItem).Name))
            {
                await Database.CreateTablesAsync(CreateFlags.None, typeof(TodoItem)).ConfigureAwait(false);                    
            }
            initialized = true;
        }
    }

    public Task<List<TodoItem>> GetItemsAsync()
    {
        return Database.Table<TodoItem>().ToListAsync();
    }

    public Task<List<TodoItem>> GetItemsNotDoneAsync()
    {
        return Database.QueryAsync<TodoItem>("SELECT * FROM [TodoItem] WHERE [Done] = 0");
    }

    public Task<TodoItem> GetItemAsync(int id)
    {
        return Database.Table<TodoItem>().Where(i => i.ID == id).FirstOrDefaultAsync();
    }

    public Task<int> SaveItemAsync(TodoItem item)
    {
        if (item.ID != 0)
        {
            return Database.UpdateAsync(item);
        }
        else
        {
            return Database.InsertAsync(item);
        }
    }

    public Task<int> DeleteItemAsync(TodoItem item)
    {
        return Database.DeleteAsync(item);
    }
}

And Constants class which contains database name and other things.以及包含数据库名称和其他内容的Constants类。

public static class Constants
{
    public const string DatabaseFilename = "TodoSQLite.db3";

    public const SQLite.SQLiteOpenFlags Flags =
        // open the database in read/write mode
        SQLite.SQLiteOpenFlags.ReadWrite |
        // create the database if it doesn't exist
        SQLite.SQLiteOpenFlags.Create |
        // enable multi-threaded database access
        SQLite.SQLiteOpenFlags.SharedCache;

    public static string DatabasePath
    {
        get
        {
            var basePath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            return Path.Combine(basePath, DatabaseFilename);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Winforms中使用c#代码将数据绑定到Winforms中的数据透视网格? - How to Bind data to Pivot grid in Winforms using c# code in Winforms? 将ListView绑定到Winforms中的列表/数据库表的最佳方法 - Best way to bind a ListView to a list / database table in winforms 是否有一个免费的wpf网格,其行为类似于winforms中的DataGridView等普通网格? - Is there a free wpf grid that behaves like normal grid like the DataGridView in winforms? 如何正确地将表格与Winforms控件绑定? - How to properly bind a table with a winforms control? Xamarin.Forms - 将模型列表绑定到网格? - Xamarin.Forms - Bind a list of models to grid? NET Winforms中如何在数据网格中绑定组合框? - How to bind combo box in data grid, in .net winforms? 有什么方法可以绑定网格视图,其中行具有类似可视化的列 - is there any way to bind the Grid View where rows having column like visualization 我的WinForms CheckBox代码出现问题 - Problem With My WinForms CheckBox Code 网格绑定然后插入到SQL表中 - Grid Bind then Insert into SQL Table 有没有办法将元素的 xaml 属性绑定到由代码创建的新元素? (c# xamarin.forms) - Is there a way to bind the xaml properties of an element to a new element created by code? (c# xamarin.forms)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM