[x]
Posted via EE Mobile

Search, ask, and monitor your questions on the go with EE Mobile. Visit Experts Exchange from your mobile device and never be out of touch again.

Question
[x]
Attachment Details
[x]
The Solution Rating System

With so many solutions, how can you tell which solutions are most likely to help you and which ones are not? To provide you with a tool to use, we rate our solutions based on various elements that most accurately determine if a solution is a quality solution. To explain what factors affect the solution rating, here are the elements we take into consideration when formulating our solution rating.

  • The Grade of the Solution
  • The Zone Rank of the Expert Providing the Solution
  • The Number of Author and Expert Comments
  • The Number of Experts Contributing
  • The Feedback of the Community

Your Input Matters
Because of the way the system is set up, the most important variable in this equation is you. As a member of Experts Exchange, you are able to cast your vote on the quality of the solutions in regard to how complete, accurate, helpful and easy to understand each solution is. When you provide your feedback, each rating is adjusted accordingly. So, if you see a solution that has a poor rating that you think is a good solution, let us know by rating it. As you do, the rating will be adjusted and will become more accurate for other members of our site.

If you have any suggestions that you would like to make for our rating system, please ask a question in the Suggestions Zone of Community Support.

Thank you!

9.6

WPF, C# - Observable Collection Problem Displaying an ItemTemplate in WPF Listbox

Asked by cardinalone in WPF and Silverlight, Microsoft Visual C#.Net

Tags: WPF, C#, XAML, Observable Collection, Object Binding

Using WPF, C# - binding an object to a WPF ListBox with a DataTemplate.

The goal is to declaratively bind an ObservableCollection class to a WPF ListBox. The LIstBox should display a collection of Images (PNG Files). The ObservableCollection class picks up image files via a FileWatcher and has a FUlLPath public property that is used to bind the SOURCE property of an IMAGE element.

However, the ListBox will not render the images. WHen I debug, the ObservableCollection class DOES populate with items, and I can access the FullPath property.

I found out via MSDN that to make my ObservableCOllection class get recognized in XAML, I had to add a namesspace in my Widnow declaration.
 
   xmlns:src="clr-namespace:Wpf_SomethingFishy"

and also a Resource for the class.

    <Window.Resources>
        <src:FishBooks x:Key="FishBooks"/>
...

because prior the ListBox
<ListBox ItemsSource="{Binding Source={StaticResource FishBooks}}

was getting a compile error :FishBooks...not found..."

But I still am not able to get the ListBox to render the class Collection items.

All COde is pasted below.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
245:
246:
247:
248:
249:
250:
251:
252:
253:
254:
255:
256:
257:
258:
259:
260:
261:
262:
263:
264:
265:
266:
267:
268:
269:
270:
271:
272:
273:
274:
275:
276:
277:
278:
279:
280:
281:
282:
283:
284:
285:
286:
287:
288:
289:
290:
291:
292:
293:
294:
295:
296:
297:
298:
299:
300:
301:
302:
303:
304:
305:
306:
307:
308:
309:
310:
311:
312:
313:
314:
315:
316:
317:
318:
319:
320:
321:
322:
323:
324:
325:
326:
327:
328:
329:
330:
331:
332:
333:
334:
335:
336:
337:
338:
339:
340:
341:
342:
343:
344:
345:
346:
347:
348:
349:
350:
351:
352:
353:
354:
355:
356:
357:
358:
359:
360:
361:
362:
363:
364:
365:
366:
367:
368:
369:
370:
371:
372:
373:
374:
375:
376:
377:
378:
379:
380:
381:
382:
383:
384:
385:
386:
387:
388:
App.XAML
<Application x:Class="Wpf_SomethingFishy.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml">
</Application>
 
APP.XAML CODE BEHIND
using System;
using System.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading;
using System.Windows;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
 
 
namespace Wpf_SomethingFishy
{
    public partial class App : Application
    {
        public App()
        {
            InitializeComponent();
 
        }
    }
}
 
 
 
FISHBOOK CLAss
using System;
using System.IO;
 
namespace Wpf_SomethingFishy
{
    public class FishBook
    {
        string name;
        DateTime dateTime;
        string size;
        string path;
 
        public FishBook(string filename)
        {
            FileInfo info = new FileInfo(filename);
            size = (info.Length / 1024).ToString("N0") + " KB";
            dateTime = info.LastWriteTime;
            name = info.Name;
            path = info.DirectoryName;
        }
 
        public string Name
        {
            get { return name; }
        }
 
        public DateTime DateTime
        {
            get { return dateTime; }
        }
 
        public string Size
        {
            get { return size; }
        }
 
        public string Path
        {
            get { return path; }
        }
 
        public string FullPath
        {
            get { return System.IO.Path.Combine(Path, Name); }
        }
 
        public override string ToString()
        {
            return FullPath;
        }
    }
}
 
 
FISHBOOKS Class
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
 
namespace Wpf_SomethingFishy
{
    public class FishBooks : ObservableCollection<FishBook>
    {
        Dictionary<string, FileSystemWatcher> watchers = new Dictionary<string, FileSystemWatcher>();
 
        public event EventHandler ItemsUpdated;
 
        protected override void ClearItems()
        {
            base.ClearItems();
            watchers.Clear();
        }
 
        protected override void InsertItem(int index, FishBook item)
        {
            base.InsertItem(index, item);
            if (!watchers.ContainsKey(item.Path))
            {
                FileSystemWatcher watcher = new FileSystemWatcher(item.Path, "*.png");
                watcher.EnableRaisingEvents = true;
                watcher.Created += new System.IO.FileSystemEventHandler(OnPhotoCreated);
                watcher.Deleted += new System.IO.FileSystemEventHandler(OnPhotoDeleted);
                watchers.Add(item.Path, watcher);
            }
        }
 
 
        void OnPhotoDeleted(object sender, System.IO.FileSystemEventArgs e)
        {
            int index = -1;
            for (int i = 0; i < Items.Count; i++)
            {
                if (Items[i].FullPath == e.FullPath)
                {
                    index = i;
                    break;
                }
            }
            if (index >= 0)
                Items.RemoveAt(index);
 
            if (ItemsUpdated != null)
                ItemsUpdated(this, new EventArgs());
        }
 
        void OnPhotoCreated(object sender, System.IO.FileSystemEventArgs e)
        {
            Items.Add(new FishBook(e.FullPath));
 
            if (ItemsUpdated != null)
                ItemsUpdated(this, new EventArgs());
        }
    }
}
 
 
FISH CONTROLLER CLass
 
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.ComponentModel;
using System.IO;
using System.Threading;
using System.Windows.Threading;
 
namespace Wpf_SomethingFishy
{
    public class FishController
    {
        public FishController()
        {
              FishBooks fishbks = new FishBooks();
 
            foreach (string s in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures).ToString() + System.IO.Path.DirectorySeparatorChar + "Fish", "*.png"))
                {
//               fishbks.ItemsUpdated += delegate { this.Dispatcher.Invoke(DispatcherPriority.Normal, new ThreadStart(Refresh)); };
                 FishBook fish = new FishBook(s);
                 fishbks.Add(fish);
                }
        }
 
 
    }
}
 
 
WINDOW1.XAML
 
<Window x:Class="Wpf_SomethingFishy.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:src="clr-namespace:Wpf_SomethingFishy"
    Title="Under the Sea" Height="750" Width="590" WindowStyle="SingleBorderWindow" Background="Transparent">
    <Window.Resources>
        <src:FishBooks x:Key="FishBooks"/>
        <LinearGradientBrush x:Key="ButtonBrushOrange" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Offset="0.45" Color="Orange" />
            <GradientStop Offset="0.45" Color="Orange" />
            <GradientStop Offset="0.6" Color="DarkOrange" />
            <GradientStop Offset="0.9" Color="DarkOrange" />
        </LinearGradientBrush>
        <LinearGradientBrush x:Key="ButtonBrushBlack" StartPoint="0,0" EndPoint="0,1">
            <GradientStop Offset="0.45" Color="DarkSlateGray"  />
            <GradientStop Offset="0.45" Color="DarkSlateGray" />
            <GradientStop Offset="0.6" Color="Black" />
            <GradientStop Offset="0.9" Color="Black" />
        </LinearGradientBrush>
        <ControlTemplate x:Key="buttonControlTemplate">
            <Grid Width="150" Height="Auto" >
                <Ellipse x:Name="Disc" Width="125" Height="125" Fill="{StaticResource ButtonBrushBlack}"></Ellipse>
                <Viewbox>
                    <ContentPresenter Margin="1" Content="{TemplateBinding Button.Content}"/>
                </Viewbox>
            </Grid>
        </ControlTemplate>
        <HierarchicalDataTemplate DataType="NavItems" ItemsSource="{Binding XPath=*}">
            <StackPanel Orientation="Horizontal">
                <Image Source="Fish\shiirafish.png" Height="42" Width="42" Margin="0,0,5,0"/>
                <TextBlock Foreground="White" FontStyle="Normal" FontFamily="Calibri" FontSize="12" Text="{Binding XPath=@Header}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="NavItem" ItemsSource="{Binding XPath=*}">
            <StackPanel Orientation="Horizontal">
                <Image Source="Fish\babelfish.png" Height="42" Width="42" Margin="0,0,5,0"/>
                <TextBlock Foreground="White" FontStyle="Normal" FontFamily="Calibri" FontSize="12" Text="{Binding XPath=@Type}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="NavItem1" ItemsSource="{Binding XPath=*}">
            <StackPanel Orientation="Horizontal">
                <Image Source="Fish\redFish.png" Height="42" Width="42" Margin="0,0,5,0"/>
                <TextBlock Foreground="White" FontStyle="Normal" FontFamily="Calibri" FontSize="12" Text="{Binding XPath=@SubType}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
        <HierarchicalDataTemplate DataType="Fish" ItemsSource="{Binding XPath=*}">
            <StackPanel Orientation="Horizontal">
                <Image Source="Fish\fish-1.png" Height="42" Width="42" Margin="0,0,5,0"/>
                <TextBlock Foreground="White" FontStyle="Normal" FontFamily="Calibri" FontSize="12" Text="{Binding XPath=Fish}"/>
            </StackPanel>
        </HierarchicalDataTemplate>
        <XmlDataProvider x:Key="BlueDataProvider" XPath="NavItems" Source="BlueNavItems.xml" />
        <Style TargetType="TreeViewItem">
            <Setter Property="IsExpanded" Value="True" />
        </Style>
    </Window.Resources>
    
    <Grid Background="{StaticResource ButtonBrushOrange}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="220"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" VerticalAlignment="Top" Height="155">
        <WrapPanel  HorizontalAlignment="Left" Grid.Column="0" >
        <Button Template="{StaticResource buttonControlTemplate}" Click="btnGo_Click" >
            <Image Source="Fish\diver.png" Height="9" Width="9" />
        </Button>
        </WrapPanel>
        </StackPanel>
        <StackPanel Margin="0,161,0,0" Grid.RowSpan="2">
            <TreeView x:Name="treeViewBlue" Grid.Row="1" Foreground="Blue" Background="{StaticResource ButtonBrushOrange}" ItemsSource="{Binding Source={StaticResource BlueDataProvider}, XPath=.}" >
            </TreeView>
        </StackPanel>
        <StackPanel Name="ListStackPanel" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Grid.Row="0" Grid.RowSpan="2" Grid.Column="2" Grid.ColumnSpan="1" >
            <ListBox x:Name="fishBox" BorderThickness="2" BorderBrush="Black"  
                     ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
                     ItemsSource="{Binding Source={StaticResource FishBooks}}" Height="45">
                <ListBox.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel Background="Blue"  />
                    </ItemsPanelTemplate>
                </ListBox.ItemsPanel>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <Grid>
                            <Grid.RowDefinitions>
                                <RowDefinition Height="55" />
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Image Source="Fish\diver.png" Height="35" Grid.Row="0" />
                        </Grid>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </StackPanel>
    </Grid>
</Window>
 
 
 
WINDOW1.XAML.CS
 
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.ComponentModel;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading;
using System.Windows.Threading;
 
 
 
namespace Wpf_SomethingFishy
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        ScaleTransform st = new ScaleTransform(3, 3);
//        object dummyNode = null;
 
        #region Window Management
 
        public Window1()
        {
            InitializeComponent();
            FishController fishcontroller = new FishController();
        }
 
        #endregion Window Management
 
 
 
 
        #region Button Events
 
        void btnGo_Click(object sender, RoutedEventArgs e)
        {
            //             AddPhotosInFolder();
         }
 
 
        #endregion Button Events
 
 
    }
 
}
 
 
BBLUE NAV ITEMS.XML - This binds via Hiearchical DataTempalte and it works
 
<?xml version="1.0" encoding="utf-8" ?>
<NavItems Header="Blue Ocean Fish">
  <NavItem Type="Big Fish">
    <NavItem1 SubType="Friendly Fish ">
        <Fish>Bottom Fish</Fish>
      </NavItem1>
    <NavItem1 SubType="Deep Sea Fish">
      <Fish>Bottom Fish</Fish>
    </NavItem1>
  </NavItem>
  <NavItem Type="Little Fish">
    <NavItem1 SubType="Friendly Fish ">
      <Fish>Bottom Fish</Fish>
    </NavItem1>
    <NavItem1 SubType="Deep Sea Fish ">
      <Fish>Bottom Fish</Fish>
    </NavItem1>
  </NavItem>
</NavItems>
 
 
The PING files in the attached ZIP were also RESOURCES in the solution so they can be used as icons for the TreeView items.
Attachments:
 
PNG FILES - used as source for the ListBox binding
 
[+][-]07/21/09 11:51 PM, ID: 24912050Accepted Solution

View this solution now by starting your 30-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

About this solution

Zones: WPF and Silverlight, Microsoft Visual C#.Net
Tags: WPF, C#, XAML, Observable Collection, Object Binding
Sign Up Now!
Solution Provided By: unmeshdave
Participating Experts: 1
Solution Grade: A
 
 
Loading Advertisement...
20091111-EE-VQP-92 - Hierarchy / EE_QW_3_20080625