如何在LongListSelector SelectionChanged方法中更改图像?

时间:2013-06-27 22:08:23

标签: c# xaml windows-phone-8 selectionchanged longlistselector

我的Windows Phone应用程序中有一个LongListSelector。 LLS为每个项目都有一个Image和TextBlock。当用户更改选择时,如何更改图像?我应该在SelectionChanged方法中写什么?

<phone:LongListSelector x:Name="MainLongListSelector" ItemsSource="{Binding Items}" SelectionChanged="MainLongListSelector_SelectionChanged">
    <phone:LongListSelector.ItemTemplate>
          <DataTemplate>
              <StackPanel Orientation="Horizontal">
                  <Image Name="PlayPause" Source="/Assets/transport.play.png"/>
                  <StackPanel>
                      <TextBlock Text="{Binding LineOne}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                  </StackPanel>
               </StackPanel>
          </DataTemplate>
    </phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>

1 个答案:

答案 0 :(得分:0)

    <phone:LongListSelector x:Name="MainLongListSelector" DataContext="{Binding listData}" IsGroupingEnabled="False" SelectionChanged="MainLongListSelector_SelectionChanged_1">
            <phone:LongListSelector.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Name="PlayPause" Source="{Binding ImgUrl}" Height="100" Stretch="Fill"/>
                        <StackPanel>
                            <TextBlock Text="{Binding ImgText}" TextWrapping="Wrap" Style="{StaticResource PhoneTextExtraLargeStyle}"/>
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </phone:LongListSelector.ItemTemplate>
        </phone:LongListSelector>

XAML背后:

    ObservableCollection<LongListData> listData = new ObservableCollection<LongListData>();

    listData.Add(new LongListData() { ImgText = "Image1", ImgUrl = new Uri("Images/1.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image2", ImgUrl = new Uri("Images/2.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image3", ImgUrl = new Uri("Images/3.jpg", UriKind.Relative) });
    listData.Add(new LongListData() { ImgText = "Image4", ImgUrl = new Uri("Images/4.jpg", UriKind.Relative) });

    MainLongListSelector.ItemsSource = listData;

在SelectionChanged方法

    private void MainLongListSelector_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var res = (sender as LongListSelector).SelectedItem as LongListData;
        int index = listData.IndexOf(res);
        //mark 1
        var newData = new LongListData() { ImgText = res.ImgText, ImgUrl = new Uri("Images/2.jpg", UriKind.Relative) };
        listData.RemoveAt(index);
        listData.Insert(index, newData);
    }

在C#代码中定义

    public class LongListData
    {
        public Uri ImgUrl { get; set; }
        public string ImgText { get; set; }
    }

您可以在代码中随机或根据需要使用“mark1”来使用图像。