0

I want to create an image in treeviewitem but I couldn't.I don't know where my error is.

#create treeviewitem's image#

            TreeViewItem tvt = new TreeViewItem();
            StackPanel stackPanel = new StackPanel();
            Label lblHeaderText = new Label();
            Label kk = new Label();
            Image imgFrontIcon;

            imgFrontIcon = new Image();


            string ImagePath = @"C:\Users\x\Desktop\y\HospitalProject\images\Untitled.png";
            if (ImagePath != null && ImagePath != string.Empty)
            {
                Uri uri = new Uri(ImagePath);
                BitmapImage bitMapSource = new BitmapImage();



                imgFrontIcon.Source = new BitmapImage(new Uri(ImagePath, UriKind.Relative));
            }

            lblHeaderText.Content = "ss";
            kk.Content = "lll";
            stackPanel.Children.Add(imgFrontIcon);
            stackPanel.Children.Add(lblHeaderText);
            stackPanel.Children.Add(kk);

            tvt.Name = "sef";
            tvt.Header = stackPanel;
            mytree.Items.Add(tvt);
  • Are you using Microsoft Visual Studio? Are you using .net? Or ASP.Net? Are you using WPF? Or Winforms? – Cullub Sep 01 '14 at 12:50
  • I am using Microsoft Visual Studio.I am using silverlight in this project. – user3296152 Sep 01 '14 at 12:54
  • You're doing it all wrong. Instead of having a bunch of code you should write a proper DataTemplate and bind the TreeView's `ItemsSource` property to a collection of appropriate data item objects. For an introduction, see the [Data Templating Overview](http://msdn.microsoft.com/en-us/library/ms742521.aspx) article on MSDN. Although it is written for WPF, it is also applicable to Silverlight. – Clemens Sep 01 '14 at 19:45
  • Then your code is a mess. Why check if `ImagePath != null && ImagePath != string.Empty` instead of just `!string.IsNullOrEmpty(ImagePath)`? Why first create an Uri and a BitmapImage and then ignore both and assign another new BitmapImage, which is created from an Uri of an absolute path, but created with `UriKind.Relative`? That doesn't make any sense. – Clemens Sep 01 '14 at 19:48
  • Next thing, a Silverlight application needs elevated trust in order to be able to access the local file system. See [this article](http://msdn.microsoft.com/en-us/library/ee721082(v=vs.95).aspx) for details. You may need to open a FileStream directly and call `BitmapImage.SetSource` instead of using an Uri. See [this answer](http://stackoverflow.com/a/24953464/1136211) for details. It's VB, not C#, but you should get the point. – Clemens Sep 01 '14 at 19:54

0 Answers0