【问题标题】:LonglistSelector binding to Image Collection does not displayLonglistSelector 绑定到图像集合不显示
【发布时间】:2014-03-21 00:43:29
【问题描述】:

我有一个 xaml 页面。 xaml 页面想要显示两个 TextBlock 和一个 LonglistSelector。

两个TextBlocks数据源来自一个对象(SpecifiedArticle);LonglistSelctor itemsSource来自Collection(ImageUriCollection)。

页面启动时,图片无法显示。

  1. 两个TextBlocks数据显示良好

  2. LonglistSelctor 不显示图像;但我确信 ImageUriCollection 的数据可以从 xaml 中获取,因为我在图像控件中进行了测试并且它可以工作

            <Image  Source="{Binding ImageUriCollection[0].ImageSource}" Width="108" Height="108" Stretch="UniformToFill">
    
    
            </Image>
    

我认为问题在于 LonglistSelctor itemsSource 绑定。有人可以帮忙吗?

以下所有代码(没有 httpclient 包装器):

DetailsPage.cs 如下:

public partial class DetailsPage : PhoneApplicationPage
    {
        DetailsPageViewModel viewModel = new DetailsPageViewModel();

        public DetailsPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(DetailsPage_Loaded);
        }

        private void DetailsPage_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = viewModel;
            //imageList.ItemsSource = viewModel.ImageUriCollection;
            //imageList.ScrollTo(imageList.ItemsSource[imageList.ItemsSource.Count - 1]);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string ArticleId = "";
            try
            {
                if (NavigationContext.QueryString.TryGetValue("ArticleId", out ArticleId))
                {
                    Debug.WriteLine(ArticleId);
                    viewModel.LoadPage(Int32.Parse(ArticleId));
                    //Debug.WriteLine(viewModel.SpecifiedArticle.Words.ToString());
                    //LayoutRoot.DataContext = new CollectionViewSource { Source = viewModel.SpecifiedArticle };
                }
                else
                {
                    MessageBox.Show("No ArticleId passed in.");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error in DetailsPage.OnNavigatedTo"); 
            }
        }
    }

ViewModel 如下:

public class DetailsPageViewModel : INotifyPropertyChanged
    {
        private bool _isLoading = false;

        public bool IsLoading
        {
            get
            {
                return _isLoading;
            }
            set
            {
                _isLoading = value;
                NotifyPropertyChanged("IsLoading");
            }
        }

        public DetailsPageViewModel()
        {
            this.SpecifiedArticle = new Article();
            this.ImageUriCollection = new ObservableCollection<Photo>();
            this.IsLoading = false;
        }

        private Article specifiedArticle;
        public Article SpecifiedArticle
        {
            get
            {
                return specifiedArticle;
            }
            set
            {
                specifiedArticle = value;
                NotifyPropertyChanged("SpecifiedArticle");
            }
        }

        public ObservableCollection<Photo> ImageUriCollection
        {
            get;
            private set;
        }

        public void LoadPage(int articleId)
        {            
            IsLoading = true;

            ReadArticle(articleId);

        }

        private async void ReadArticle(int articleId)
        {
            try
            {
                Article articleDetails = new Article();
                articleDetails = await CollectionHttpClient.GetAsyncByArticleId(articleId);
                SpecifiedArticle = articleDetails;
                //articleDetails.FirstImage = new Uri(articleDetails.ImagePathList[0]);

                if (articleDetails.ImagePathList != null)
                {
                    foreach (var item in articleDetails.ImagePathList)
                    {
                        Photo p = new Photo();
                        p.ImageSource = new Uri(item);
                        this.ImageUriCollection.Add(p);
                    }
                    //var image = await CollectionHttpClient.GetImageByImageName(articleDetails.ImagePath);
                    //Bytelist.Add(image);
                }
                else
                {
                    this.ImageUriCollection = null;
                }

                IsLoading = false;


            }
            catch(Exception ex)
            {
                MessageBox.Show("sorry, no data.");
                IsLoading = false;
            }

        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

xaml 是:

<phone:PhoneApplicationPage.Resources>

        <vm:DetailsPageViewModel x:Key="viewModel"/>
        <phone:JumpListItemBackgroundConverter x:Key="BackgroundConverter"/>
        <phone:JumpListItemForegroundConverter x:Key="ForegroundConverter"/>

        <Style x:Key="JumpListStyle" TargetType="phone:LongListSelector">
            <Setter Property="LayoutMode" Value="List" />
            <Setter Property="Margin" Value="12,12,0,0"/>
            <Setter Property="ItemTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <Border Background="{Binding Converter={StaticResource BackgroundConverter}}" 
                                Width="470" 
                                Height="70" 
                                Margin="6">
                            <TextBlock Text="{Binding Key}"
                                       Foreground="{Binding Converter={StaticResource ForegroundConverter}}"                                       
                                       FontFamily="{StaticResource PhoneFontFamilySemiBold}"
                                       FontSize="28"  
                                       Padding="2"
                                       VerticalAlignment="Bottom"/>
                        </Border>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>

        <DataTemplate x:Key="GroupHeader">
            <Border Background="Transparent">
                <Border Background="Transparent" BorderBrush="Transparent" BorderThickness="1"  
                        Width="400" Height="90"                  
                        HorizontalAlignment="Left">
                    <TextBlock Text="Pictures:" 
                               Foreground="{StaticResource PhoneAccentBrush}" 
                               FontSize="28"
                               Padding="2"                                
                               FontFamily="{StaticResource PhoneFontFamilySemiLight}"
                               HorizontalAlignment="Left"
                               VerticalAlignment="Center"/>
                </Border>
            </Border>
        </DataTemplate>

        <DataTemplate x:Key="ItemTemplate">
            <StackPanel Height="108" Width="108" Margin="6,6">
                <Image Width="108" Height="108" Stretch="UniformToFill">
                    <Image.Source>
                        <BitmapImage UriSource="{Binding ImageSource}" CreateOptions="BackgroundCreation"/>
                    </Image.Source>
                </Image>
            </StackPanel>
        </DataTemplate>


    </phone:PhoneApplicationPage.Resources>

    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel Grid.Row="0" Margin="12,17,0,28">
            <TextBlock Text="{Binding Path=SpecifiedArticle.Subject }" TextWrapping="Wrap" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

        </StackPanel>

        <!--ContentPanel - place images here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Background="Transparent">

            <!--
            <Image  Source="{Binding ImageUriCollection[0].ImageSource}" Width="108" Height="108" Stretch="UniformToFill">

                    <Image.Source>
                        <BitmapImage UriSource="{Binding ImageSource}" CreateOptions="BackgroundCreation"/>
                    </Image.Source>

            </Image>
 -->

            <phone:LongListSelector Name="imageList" Margin="13,-30,0,0"
                                        ItemsSource="{Binding ImageUriCollection}"
                                        ItemTemplate="{StaticResource ItemTemplate}"                     

                                        JumpListStyle="{StaticResource JumpListStyle}" 
                                        IsGroupingEnabled="True"
                                        LayoutMode="Grid" 
                                        GridCellSize="108,108"/>

        </Grid>

        <!--ContentPanel - place article words here-->
        <StackPanel Grid.Row="2" Margin="12,17,0,28">

            <TextBlock Text="{Binding Path=SpecifiedArticle.Words}" TextWrapping="Wrap" Style="{StaticResource PhoneTextNormalStyle}"/>
        </StackPanel>



    </Grid>

DetailsPage.cs 如下:

public partial class DetailsPage : PhoneApplicationPage
    {
        DetailsPageViewModel viewModel = new DetailsPageViewModel();

        public DetailsPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(DetailsPage_Loaded);
        }

        private void DetailsPage_Loaded(object sender, RoutedEventArgs e)
        {
            DataContext = viewModel;
            //imageList.ItemsSource = viewModel.ImageUriCollection;
            //imageList.ScrollTo(imageList.ItemsSource[imageList.ItemsSource.Count - 1]);
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            string ArticleId = "";
            try
            {
                if (NavigationContext.QueryString.TryGetValue("ArticleId", out ArticleId))
                {
                    Debug.WriteLine(ArticleId);
                    viewModel.LoadPage(Int32.Parse(ArticleId));
                    //Debug.WriteLine(viewModel.SpecifiedArticle.Words.ToString());
                    //LayoutRoot.DataContext = new CollectionViewSource { Source = viewModel.SpecifiedArticle };
                }
                else
                {
                    MessageBox.Show("No ArticleId passed in.");
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error in DetailsPage.OnNavigatedTo"); 
            }
        }
    }

ViewModel 如下:

public class DetailsPageViewModel : INotifyPropertyChanged
    {
        private bool _isLoading = false;

        public bool IsLoading
        {
            get
            {
                return _isLoading;
            }
            set
            {
                _isLoading = value;
                NotifyPropertyChanged("IsLoading");
            }
        }

        public DetailsPageViewModel()
        {
            this.SpecifiedArticle = new Article();
            this.ImageUriCollection = new ObservableCollection<Photo>();
            this.IsLoading = false;
        }

        private Article specifiedArticle;
        public Article SpecifiedArticle
        {
            get
            {
                return specifiedArticle;
            }
            set
            {
                specifiedArticle = value;
                NotifyPropertyChanged("SpecifiedArticle");
            }
        }

        public ObservableCollection<Photo> ImageUriCollection
        {
            get;
            private set;
        }

        public void LoadPage(int articleId)
        {            
            IsLoading = true;

            ReadArticle(articleId);

        }

        private async void ReadArticle(int articleId)
        {
            try
            {
                Article articleDetails = new Article();
                articleDetails = await CollectionHttpClient.GetAsyncByArticleId(articleId);
                SpecifiedArticle = articleDetails;
                //articleDetails.FirstImage = new Uri(articleDetails.ImagePathList[0]);

                if (articleDetails.ImagePathList != null)
                {
                    foreach (var item in articleDetails.ImagePathList)
                    {
                        Photo p = new Photo();
                        p.ImageSource = new Uri(item);
                        this.ImageUriCollection.Add(p);
                    }
                    //var image = await CollectionHttpClient.GetImageByImageName(articleDetails.ImagePath);
                    //Bytelist.Add(image);
                }
                else
                {
                    this.ImageUriCollection = null;
                }

                IsLoading = false;


            }
            catch(Exception ex)
            {
                MessageBox.Show("sorry, no data.");
                IsLoading = false;
            }

        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(String propertyName)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (null != handler)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }

【问题讨论】:

    标签: xaml windows-phone-7 windows-phone-8 binding longlistselector


    【解决方案1】:

    试试这个-

    只需将您的 ItemTemplate DataTemplate 更改为更简单的一个

    如果可行,请一次添加一项更改。

    <DataTemplate x:Key="ItemTemplate">
        <Image Source="{Binding ImageSource}" Stretch="UniformToFill"/>
    </DataTemplate>
    

    【讨论】:

    • @max 你能看到列表被填充了吗?我的意思是列表中有任何项目吗?
    • 是的,我确定,列表中有项目。正如我所说,如果我删除 longlistselector,我只使用图像,它很好并且可以获得绑定数据。当我使用 longlistselector 并将图像控件放入 longlistselector 时,它会失败
    • @max 我说的是 LongListSelector 被填充,检查这个 -> ItemsSource="{Binding ImageUriCollection}" 通过更改 LongListSelector 并通过更改上述数据模板来检查它以包含其他一些可见元素,例如带有一些修复文本的文本块,以便在填充 LongListSelector 时,您可以看到绑定中只有问题
    • 即使我在 DataTemplate 中设置了 ,它什么也没显示,似乎是 longlistselector 的问题,你还有其他的吗想法?
    【解决方案2】:

    这是风格问题。

    删除样式,重试,图片显示良好

    <phone:LongListSelector Name="imageList" Margin="13,-30,0,0" 
                                        ItemsSource="{Binding ImageUriCollection}"
                                        ItemTemplate="{StaticResource ItemTemplate}"
                                        LayoutMode="Grid"
                                        GridCellSize="108,108">
    
                </phone:LongListSelector>
    

    在JumpListStyle中,它包含不属于xaml的文本块,这就是LonglistSelector在集合绑定后不显示任何内容的原因。

    【讨论】:

      猜你喜欢
      • 2014-05-30
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      相关资源
      最近更新 更多