来自ListView

时间:2018-05-14 12:18:36

标签: c# xaml xamarin xamarin.forms xamarin.ios

我创建了以下SQLite表。

public class Settings
{

    public string Name { get; set; }

    [MaxLength(255)]
    public string Value { get; set; }
}

SQLite表填入以下代码。

public partial class SQL : ContentPage
{
    private SQLiteAsyncConnection _connection;
    private ObservableCollection<Settings> _settings;

    public SQL()
    {
        InitializeComponent();


        _connection = DependencyService.Get<ISQLiteDb>().GetConnection();
    }

    protected override async void OnAppearing()
    {
        await _connection.CreateTableAsync<Settings>();

        var settings_name = new Settings { Name = "Meaning of Life", Value = "42" };
        await _connection.InsertAsync(settings_name);

        await DisplayAlert("Alert", "Value Added to database!", "OK");


        var settings = await _connection.Table<Settings>().ToListAsync();
        _settings = new ObservableCollection<Settings>(settings);
        ListView.ItemsSource = _settings;

        base.OnAppearing();
    }

    void MyItemTapped (object sender, System.EventArgs e)
    {
        DisplayAlert("Alert", e.ToString(), "OK");
    }
}

然后将其放入带有以下XAML

的ListView中
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="BudgetBuddy.SQL">
    <ContentPage.Content>
                <ListView x:Name="ListView" ItemTapped="MyItemTapped" ItemSelected="MyItemSelected">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextCell Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </ContentPage.Content>
</ContentPage>

我的问题是,当有人按下项目时,我将如何显示值42&#34; Life of Life&#34;在ListView?

我为e.ToString()尝试了不同的东西,例如e.Item但在System.EventArgs中不存在。我认为我需要检查与System.EventArgs不同的东西。我认为System.EventArgs被称为命名空间,这是正确的吗?我怎么知道我可以选择哪些其他有效选项?

2 个答案:

答案 0 :(得分:2)

尝试在&#34; ItemSelected&#34;上进行事件

    private void MyItemSelected(object sender, SelectedItemChangedEventArgs e)
    {
        var selected = e.SelectedItem as Settings;
        DisplayAlert("Alert", selected.Value, "OK");
    }

答案 1 :(得分:0)

Anastasia's answer几乎是正确的。我使用ItemTappedEvent代替并进行了小幅调整以访问对象:

private void MyItemSelected(object sender, Xamarin.Forms.ItemTappedEventArgs e)
{
    var settings = e.Item as Settings;
    DisplayAlert("Alert",  settings.Value, "OK");
}