e.SelectedItem.ToString()生成类名Xamarin.Forms

时间:2018-03-20 17:25:29

标签: xaml listview xamarin xamarin.forms selecteditem

我是Xamarin.Forms的新手,尽管我搜索过,但我在ListView中获取与所选项目可绑定属性相关联的字符串失败了。目标是根据所选项目采取行动。我在XAML中定义了我的UI,如下所示:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="EdgeNet.EdgeNetAddModule">
<StackLayout Padding="10">
    <Label Text="" FontSize="12" />
    <Label Text="Add Module" TextColor="#00A79D" HorizontalOptions="Center" FontSize="36"/>
    <Label Text="" FontSize="12"/>
    <ListView x:Name="moduleTypesListView"
        HorizontalOptions="FillAndExpand" 
        VerticalOptions="FillAndExpand" 
        Header="Select A Module" 
        ItemSelected="OnSelection"
        RowHeight="80">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextCell Text="{Binding Name}" TextColor="#00A79D" Detail="{Binding Detail}" DetailColor="#A7A9AC"/>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Image Source="Logo.png" />

我已将listview绑定到代码隐藏中的ObservableCollection,如下所示:

 moduleTypesListView.ItemsSource = new ObservableCollection<Products>()
        {
            new Products {Name = "Outlet", Detail = "Standard 3-Prong Residential"},
            new Products {Name = "Switch", Detail = "Standard Wall Switch"},
            new Products {Name = "Thermostat", Detail = "edgeNet Smart Thermostat"}
        };

我想根据所选项目打开特定活动。我的事件处理程序如下:e.SelectedItem.ToString()返回&#34; EdgeNet.Products&#34;对于任何选定的项目:

        void OnSelection(object sender, SelectedItemChangedEventArgs e)
    {
        if (e.SelectedItem == null)
        {
            return; //ItemSelected is called on deselection, which results in SelectedItem being set to null
        }

        Console.WriteLine(e.SelectedItem.ToString()); //This outputs the class name Products

        //Disable visual ugly orange highlighter for selected item
        ((ListView)sender).SelectedItem = null;

        //ToDo: Figure out which item was selected and start setup routine
    }

提前感谢您的帮助。我确定我在这里遗漏了一些简单的东西,但不确定它是什么。

1 个答案:

答案 0 :(得分:2)

e.SelectedItemProduct,因此您可以投放它然后访问它的属性

var product = (Product) e.SelectedItem;

if (product.Name == "blah") {
  ...
}