我只想在ListView中获取所选项目。
这是XAML:
<TabItem Header="Musique" Background="#1874CD" BorderBrush="#68838B">
<ListView x:Name="ListM" Width="Auto" Background="#D1EEEE" ItemsSource="{Binding Path=MediaCollection}" Margin="-8,-0.877,-1,-2.925" SelectionChanged="ListM_SelectionChanged">
<ListView.View>
<GridView AllowsColumnReorder="True" >
<GridViewColumn Header="" Width="Auto" >
<GridViewColumn.CellTemplate>
<DataTemplate>
<Image Name="IconImage" Source="{Binding IconUri}" Panel.ZIndex="2" Width="15" Height="15"></Image>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn DisplayMemberBinding="{Binding Title}" Header="Titre" Width="auto" />
<GridViewColumn DisplayMemberBinding="{Binding Composer}" Header="Artiste" Width="70" />
<GridViewColumn DisplayMemberBinding="{Binding Length}" Header="Durée" Width="50" />
<GridViewColumn DisplayMemberBinding="{Binding Album}" Header="Album" Width="70" />
</GridView>
</ListView.View>
</ListView>
我用这段代码插入项目:
ListM.Items.Add(new ListGrid() { IconUri = imagemp3.Source, Title = Ftitle, Length = duration, Album = Falbum, Composer = Fcomposer });
当我在列表中选择一个项目时,我需要获取这些详细信息(Title
,Length
,...)。我已经尝试但有许多问题但它仍然无效。
答案 0 :(得分:0)
只需将SelectedItem
投射到您的类型:
private void ListM_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var listgrid = (ListGrid)ListM.SelectedItem;
}
但似乎你在混合某些东西。您正在使用DataBinding(ItemsSource
),但您也手动添加项目。
最好只使用DataBinding,方法是将项目添加到ViewModel中的MediaCollection
,并将SelectedItem
绑定到ViewModel中的另一个属性:
:
SelectedItem="{Binding SelectedItem}"
答案 1 :(得分:0)
使用SelectedItems:
SelectedItems是所选行的集合,
如果您只想获得标题:
string age = ListM.SelectedItems[0].SubItems[0].Text;
如果您想获得所有细节:
ListM.SelectedItems [0]返回一个对象。首先需要将其强制转换为特定类型,然后才能访问其成员。 创建一个Media类(Title,Composer ...),然后:
private void getSelectedIteminListView(object sender, MouseButtonEventArgs e)
{
Media media = (Media)ListM.SelectedItems[0];
}
不要忘记添加活动:
ListM.DoubleClick += getSelectedIteminListView;
答案 2 :(得分:0)
我最后听@ M.REJEB
private void ListM_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListGrid media = (ListGrid)ListM.SelectedItems[0];
string age = media.Title;
MessageBox.Show("Selected : " + age);
}
它适用于这个类:
class ListGrid
{
public string Path { get; set; }
public string Title { get; set; }
public System.TimeSpan Length { get; set; }
public string Album { get; set; }
public string Composer { get; set; }
public System.Windows.Media.ImageSource IconUri { get; set; }
}