0

I am new to WPF having previously worked with WinForms on occasion and I still trying to get my head around the WPF mentality, which given my background is embedded coding, seems quite removed.

In my project I need to create a Grid Panel "template", which I'll call "Fred" (where in this case Fred is simply a cluster of graphically customized buttons) and spawn multiple instances of this to the UI programmatically based on external events. I am finding it hard to see an obvious way to do this (perhaps that is because there maybe multiple ways?) and have looked into ControlTemplates, Styles and Custom Elements. I suspect the solution lies in the latter but I am also concerned I might be thinking about this in the wrong way. To me it seems to make sense to visualize Fred as a Grid resource that I can programmatically invoke somehow when I need to create a new instance, but given I found it hard to "google" this very thing then perhaps I am going about this all wrong?

I apologies if this is a bit vague.

My question here is two fold:

  1. Is this a sensible way to achieve my end goal i.e. if I need to programmatically spawn this cluster of customized Buttons (Fred) then does it make sense to contain these in a Grid that can be accessed by the main C# or is there a more standard way that I am missing to achieve this?

  2. Depending on the answer to (1) are there code examples to achieve this?

Vadim Sentiaev
  • 741
  • 4
  • 18
Matt
  • 27
  • 2

1 Answers1

0

The concept you are looking for is an "ItemsControl" (which is itself a usable class, and also has several derived classes like ListView and ListBox) in combination with DataTemplates.

In this case you would make "Fred" a DataTemplate (commonly as the direct descendant of your ItemControls ItemTemplate property in XAML). You then bind ItemsSource to a collection (should be ObservableCollection<T> for runtime additions/deletions).

All of this relies on using the MVVM pattern (which coming from WinForms you probably aren't). I would suggest looking at MSDN, Stack Overflow, an excellent blog series by Reed Copsey: http://reedcopsey.com/series/windows-forms-to-mvvm/ or just google "WPF and MVVM" to learn more.

To answer your questions explicitly:

  1. Yes; you have the right concept but are thinking about it in WinForms terms/practices. Use MVVM instead.
  2. Yes; there are many resources available.
BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117