9 Replies - 31597 Views - Last Post: 08 November 2013 - 04:54 AM Rate Topic: -----

#1 KFredje  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 06-September 11

Putting items in listview with image and name

Posted 27 December 2011 - 02:01 AM

Hello,

So I'm trying some new stuff out in WPF but I'm used to program in C#.

My goal is to convert my created application in C# to WPF cause here I can use the windows ribbon.

So in C# I used a listview to get my goal and the following code to get a image and underneath a name:
public void ListView(string sContiain)
        {
            ContextMenuStrip mnu = new ContextMenuStrip();
            ToolStripMenuItem mnuAdd = new ToolStripMenuItem("Add");
            ToolStripMenuItem mnuEdit = new ToolStripMenuItem("Edit");
            ToolStripMenuItem mnuInfo = new ToolStripMenuItem("Info");
            mnuAdd.Click += new EventHandler(mnuAdd_Click);
            mnuEdit.Click += new EventHandler(mnuEdit_Click);
            mnuInfo.Click += new EventHandler(mnuInfo_Click);
            mnu.Items.AddRange(new ToolStripItem[] { mnuAdd, mnuEdit, mnuInfo });

            imageListLarge.Images.Clear();
            lsvMovies.Clear();

            imageListLarge.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
            imageListLarge.ImageSize = new System.Drawing.Size(100, 148);

            for (index = 0; index < dt.Rows.Count; index++)
            {
                if (dt.Rows[index]["MovieTitle"].ToString().ToLower().Contains(sContiain))
                {
                    using (Image temp = Image.FromFile(dt.Rows[index]["CoverFile"].ToString()))
                    {
                        imageListLarge.Images.Add(index.ToString(), (Image)temp.Clone());
                    }
                    GC.Collect();
                }
            }

            lsvMovies.LargeImageList = imageListLarge;

            for (index = 0; index < dt.Rows.Count; index++)
            {
                if (dt.Rows[index]["MovieTitle"].ToString().ToLower().Contains(sContiain))
                {
                    ListViewItem listItem = new ListViewItem(dt.Rows[index]["MovieTitle"].ToString(), index.ToString());
                    lsvMovies.ContextMenuStrip = mnu;
                    lsvMovies.Items.Add(listItem);
                }

                lsvMovies.Click += new EventHandler(InfoClick);
                lsvMovies.DoubleClick += new EventHandler(SelectMovie);
            }
        }


In WPF, unfortunately, this isn't working. I searched the internet for some good alternatives and found a guide with a listbox used to do this but there was no name underneath the picture and it gave me errors when I tried the demo file.

Does anyone has a good guide about this or can explain me how I can build my code again? The data used is from a datatable.

Is This A Good Question/Topic? 0
  • +

Replies To: Putting items in listview with image and name

#2 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 428
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: Putting items in listview with image and name

Posted 27 December 2011 - 02:49 AM

Here is a working WPF sample how to have both text and image in a listbox. You can also add buttons and every other kinds of controls in the ItemTemplate of ListBox too if you want to:

XAML:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" x:Name="window1">
    <window.Resources>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" />
    </Grid>
</Window>



Code behind in C#:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Mainwindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            MyImages = new ObservableCollection<MyImageClass>();
            InitializeComponent();

            MyImages.Add(new MyImageClass("earth", GetImageFromResourceString("earth")));
            MyImages.Add(new MyImageClass("mercury", GetImageFromResourceString("mercury")));
            MyImages.Add(new MyImageClass("venus", GetImageFromResourceString("venus")));
        }

        public ObservableCollection<MyImageClass> MyImages { get; set; }

        private BitmapImage GetImageFromResourceString(string imageName)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri("pack://application:,,,/WpfApplication1;component/Resources/" + imageName + ".jpg");
            image.EndInit();
            return image;
        }


    }

    public class MyImageClass
    {
        public MyImageClass(string title, ImageSource image)
        {
            this.Title = title;
            this.Image = image;
        }

        public string Title { get; set; }

        public ImageSource Image { get; set; }
    }
}



I have attached a screenshot of the application so you can see what the outcome should look like.

The images I get with GetImageFromResourceString function are in Resources folder of my project and their build action is set to Resource.

Let me know if you need more help with this.

Attached image(s)

  • Attached Image

Was This Post Helpful? 1
  • +
  • -

#3 KFredje  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 06-September 11

Re: Putting items in listview with image and name

Posted 28 December 2011 - 07:07 AM

thanks a lot for the reply. I was out of town yesterday and will try your code tonight. I'll let you know I need more help.

Maybe 1 thing already, can the images/names be ordered from right to left like if you explore a folder in windows?
Was This Post Helpful? 0
  • +
  • -

#4 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 428
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: Putting items in listview with image and name

Posted 28 December 2011 - 07:37 AM

Sure, it's possible. You have to edit ListBox's ItemsPanel's template to WrapPanel to make it wrap like in windows explorer's file view.

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" x:Name="window1">
    <window.Resources>
        <Style TargetType="ListBox">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid Width="100" Height="100">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    <Grid >
        <ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
    </Grid>
</Window>




I attached another picture to show the results.

EDIT:
Using WrapPanel isn't required if you just want to align images from left to right, you can use ListBox's Orientation property for that. But if you do that, you won't get the Wrapping you get with using WrapPanel which is probably what you want if you want to show images like in explorer's folder.

Attached image(s)

  • Attached Image

This post has been edited by janne_panne: 28 December 2011 - 07:39 AM

Was This Post Helpful? 0
  • +
  • -

#5 KFredje  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 06-September 11

Re: Putting items in listview with image and name

Posted 28 December 2011 - 08:01 AM

I have tried out your code (first post) and changed some stuff to suit my needs, however, when I build and run the application I get following error:

Quote

System.Reflection.TargetInvocationException was unhandled
Message=Exception has been thrown by the target of an invocation.
Source=mscorlib
StackTrace:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
at System.Xaml.Schema.XamlTypeInvoker.CreateInstance(Object[] arguments)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstanceWithCtor(XamlType xamlType, Object[] args)
at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
at System.Xaml.XamlObjectWriter.WriteStartMember(XamlMember property)
at System.Xaml.XamlWriter.WriteNode(XamlReader reader)
at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
at System.Windows.Application.LoadBamlStreamWithSyncInfo(Stream stream, ParserContext pc)
at System.Windows.Application.LoadComponent(Uri resourceLocator, Boolean bSkipJournaledProperties)
at System.Windows.Application.DoStartup()
at System.Windows.Application.<.ctor>b__1(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at Doga.App.Main() in D:\Documents\School 2011 - 2012\Softwareontwikkeling\Doga\Doga\obj\x86\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.NullReferenceException
Message=Object reference not set to an instance of an object.
Source=Doga
StackTrace:
at Doga.Mainwindow..ctor() in D:\Documents\School 2011 - 2012\Softwareontwikkeling\Doga\Doga\Mainwindow.xaml.cs:line 47
InnerException:

EDIT: The error appear to occur at InitializeComponent(); in the C# code.
Since my knowledge of WPF is very low I don't know what caused this error.

This are my XAML:
<ribbon:RibbonWindow x:Class="Doga.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
        Title="MainWindow"
		x:Name="RibbonWindow"
		Width="640" Height="480" Loaded="RibbonWindow_Loaded">

    <window.Resources>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    
	<Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        
<ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" Grid.Row="1" />
   
    </Grid>
</ribbon:RibbonWindow>



and this is my C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using Microsoft.Windows.Controls.Ribbon;

namespace Doga
{
    /// <summary>
    /// Interaction logic for Mainwindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {
        string user = Environment.UserName;
        DataTable dt = new DataTable();
        clsDataCode DataCode = new clsDataCode();
        int index;
        public ObservableCollection<MyImageClass> MyImages { get; set; }

        public MainWindow()
        {
MyImages = new ObservableCollection<MyImageClass>();
            InitializeComponent();

            if (!Directory.Exists(@"C:\Users\" + user + @"\AppData\Local\KFredje & Co\Doga\Thumbs"))
                Directory.CreateDirectory(@"C:\Users\" + user + @"\AppData\Local\KFredje & Co\Doga\Thumbs");
            if (!File.Exists(@"C:\Users\" + user + @"\AppData\Local\KFredje & Co\Doga\Doga.doga"))
                DataCode.CreateFile(@"C:\Users\" + user + @"\AppData\Local\KFredje & Co\Doga\Doga.doga");
            dt = DataCode.LoadData;

            for (index = 0; index < dt.Rows.Count; index++)
            {
                MyImages.Add(new MyImageClass(dt.Rows[index]["MovieTitle"].ToString(), GetImageFromCoverFile(dt.Rows[index]["CoverFile"].ToString())));
            }
        }

        private BitmapImage GetImageFromCoverFile(string CoverFile)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri(CoverFile);
            image.EndInit();
            return image;
        }

        public class MyImageClass
        {
            public MyImageClass(string title, ImageSource image)
            {
                this.Title = title;
                this.Image = image;
            }

            public string Title { get; set; }
            public ImageSource Image { get; set; }
        }

        private void RibbonWindow_Loaded(object sender, RoutedEventArgs e)
        {

        }
    }
}


This post has been edited by KFredje: 28 December 2011 - 08:11 AM

Was This Post Helpful? 0
  • +
  • -

#6 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 428
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: Putting items in listview with image and name

Posted 28 December 2011 - 08:21 AM

Try debugging your MainWindow constructor, that's where the error seems to be according to the error message (NullReferenceException).

Maybe your DataCode.LoadData is null and then you are trying to iterate through the rows in dt which is null and that would cause the exception.
Was This Post Helpful? 0
  • +
  • -

#7 KFredje  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 131
  • Joined: 06-September 11

Re: Putting items in listview with image and name

Posted 28 December 2011 - 08:37 AM

This is the error what I get when I'm debugging and when the node is at InitializeComponent(); and I press F11 to go to next line:Attached Image

I also think my XAML file is wrong
<ribbon:RibbonWindow x:Class="Doga.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary"
        Title="MainWindow"
		x:Name="RibbonWindow"
		Width="640" Height="480">

    <window.Resources>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    
	<Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <ribbon:Ribbon x:Name="Ribbon">
            <ribbon:Ribbon.ApplicationMenu>
                <ribbon:RibbonApplicationMenu SmallImageSource="Images\SmallIcon.png">
                    <ribbon:RibbonApplicationMenuItem Header="Hello _Ribbon"
                                                      x:Name="MenuItem1"
                                                      ImageSource="Images\LargeIcon.png"/>
                </ribbon:RibbonApplicationMenu>
            </ribbon:Ribbon.ApplicationMenu>
            <ribbon:RibbonTab x:Name="HomeTab" 
                              Header="Home">
                <ribbon:RibbonGroup x:Name="Group1" 
                                    Header="Group1">
                    <ribbon:RibbonButton x:Name="Button1"
                                         LargeImageSource="Images\LargeIcon.png"
                                         Label="Button1" />

                    <ribbon:RibbonButton x:Name="Button2"
                                         SmallImageSource="Images\SmallIcon.png"
                                         Label="Button2" />
                    <ribbon:RibbonButton x:Name="Button3"
                                         SmallImageSource="Images\SmallIcon.png"
                                         Label="Button3" />
                    <ribbon:RibbonButton x:Name="Button4"
                                         SmallImageSource="Images\SmallIcon.png"
                                         Label="Button4" />
                    
                </ribbon:RibbonGroup>
                
            </ribbon:RibbonTab>
        </ribbon:Ribbon>

        <ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" Grid.Row="1" Background="#FFE40000"></ListBox>
    </Grid>
</ribbon:RibbonWindow>


This post has been edited by KFredje: 28 December 2011 - 10:36 AM

Was This Post Helpful? 0
  • +
  • -

#8 janne_panne  Icon User is offline

  • WinRT Dev
  • member icon

Reputation: 428
  • View blog
  • Posts: 1,047
  • Joined: 09-June 09

Re: Putting items in listview with image and name

Posted 28 December 2011 - 01:20 PM

I don't have VS on this computer at the moment so I can't create a similar application.

If I were you, I would create a new application with just an empty form, no code behind logic or any controls. Make it the same type as you have now (RibbonWindow).
Was This Post Helpful? 0
  • +
  • -

#9 prashanth.mp7  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 1
  • Joined: 10-June 12

Re: Putting items in listview with image and name

Posted 10 June 2012 - 03:23 AM

View Postjanne_panne, on 28 December 2011 - 01:20 PM, said:

I don't have VS on this computer at the moment so I can't create a similar application.

If I were you, I would create a new application with just an empty form, no code behind logic or any controls. Make it the same type as you have now (RibbonWindow).

Hi,i tried modifying your code like this,but the images are not getting displayed,I just see a blank window.can you help me on this please.

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyImages = new ObservableCollection<MyImageClass>();
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = true;
            ofd.Filter = "Image Files (*.jpg, *.bmp,*.png,*.gif)|*.jpg;*.bmp;*.png;*.gif|All Files|*.*";
            if (ofd.ShowDialog() == true)
            {
                string[] filePath = ofd.FileNames;
                int i = filePath.Length;
                string[] safeFilePath = ofd.SafeFileNames;
                foreach (string imgPath in filePath)
                {
                    foreach (string filename in safeFilePath)
                    {
                        MyImages.Add(new MyImageClass(filename, GetImageFromResourceString(imgPath)));
                    }
                }
            }

            //MyImages.Add(new MyImageClass("earth", GetImageFromResourceString("earth")));
            //MyImages.Add(new MyImageClass("mercury", GetImageFromResourceString("mercury")));
            //MyImages.Add(new MyImageClass("venus", GetImageFromResourceString("venus")));
        }
        public ObservableCollection<MyImageClass> MyImages { get; set; }

        private BitmapImage GetImageFromResourceString(string imageName)
        {
            BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.UriSource = new Uri(imageName);
                    image.EndInit();
            return image; 
        }


    }

    public class MyImageClass
    {
        public MyImageClass(string title, ImageSource image)
        {
            this.Title = title;
            this.Image = image;
        }

        public string Title { get; set; }

        public ImageSource Image { get; set; }
    }
[code]<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" x:Name="window1"
         xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase">
    <window.Resources>
        <Style TargetType="ListBox">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid Width="100" Height="100">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image, diag:PresentationTraceSources.TraceLevel=High}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    <Grid >
        <ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
    </Grid>
</Window>


Thanks and regards,
Prashanth MP
Was This Post Helpful? 1
  • +
  • -

#10 chaosniu2003  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 08-November 13

Re: Putting items in listview with image and name

Posted 08 November 2013 - 04:54 AM

View Postprashanth.mp7, on 10 June 2012 - 03:23 AM, said:

View Postjanne_panne, on 28 December 2011 - 01:20 PM, said:

I don't have VS on this computer at the moment so I can't create a similar application.

If I were you, I would create a new application with just an empty form, no code behind logic or any controls. Make it the same type as you have now (RibbonWindow).

Hi,i tried modifying your code like this,but the images are not getting displayed,I just see a blank window.can you help me on this please.

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            MyImages = new ObservableCollection<MyImageClass>();
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = true;
            ofd.Filter = "Image Files (*.jpg, *.bmp,*.png,*.gif)|*.jpg;*.bmp;*.png;*.gif|All Files|*.*";
            if (ofd.ShowDialog() == true)
            {
                string[] filePath = ofd.FileNames;
                int i = filePath.Length;
                string[] safeFilePath = ofd.SafeFileNames;
                foreach (string imgPath in filePath)
                {
                    foreach (string filename in safeFilePath)
                    {
                        MyImages.Add(new MyImageClass(filename, GetImageFromResourceString(imgPath)));
                    }
                }
            }

            //MyImages.Add(new MyImageClass("earth", GetImageFromResourceString("earth")));
            //MyImages.Add(new MyImageClass("mercury", GetImageFromResourceString("mercury")));
            //MyImages.Add(new MyImageClass("venus", GetImageFromResourceString("venus")));
        }
        public ObservableCollection<MyImageClass> MyImages { get; set; }

        private BitmapImage GetImageFromResourceString(string imageName)
        {
            BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.UriSource = new Uri(imageName);
                    image.EndInit();
            return image; 
        }


    }

    public class MyImageClass
    {
        public MyImageClass(string title, ImageSource image)
        {
            this.Title = title;
            this.Image = image;
        }

        public string Title { get; set; }

        public ImageSource Image { get; set; }
    }
[code]<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" x:Name="window1"
         xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase">
    <window.Resources>
        <Style TargetType="ListBox">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <WrapPanel />
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <DataTemplate x:Key="MyImagesItemTemplate">
            <Grid Width="100" Height="100">
                <Grid.RowDefinitions>
                    <RowDefinition Height="auto" />
                    <RowDefinition Height="auto" />
                </Grid.RowDefinitions>
                <Image Grid.Row="0" Source="{Binding Path=Image, diag:PresentationTraceSources.TraceLevel=High}" />
                <Label Grid.Row="1" Content="{Binding Path=Title}" />
            </Grid>
        </DataTemplate>
    </window.Resources>
    <Grid >
        <ListBox ItemsSource="{Binding Path=MyImages, ElementName=window1}" ItemTemplate="{StaticResource MyImagesItemTemplate}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />
    </Grid>
</Window>


Thanks and regards,
Prashanth MP


Hi!I tried your code in my computer.You can edit code like this:
...
MyImages = new ObservableCollection<MyImageClass>();
InitializeComponent();
...
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1