• 0

[C# WPF] Dynamically adding items to content


Question

Hello gang,

I am playing around with WPF and I cannot find out how to dynamically add multiple items to the Content. I need to have to TextBlocks and two images on a UserControl.

"MenuCount" and "MenuText" are two TextBlocks that are declared within the class and can be modified via properties.

The code I have so far is:


public MainPage()
: base()
{
InitializeComponent();
DataContext = this;

MenuText.Text = "Menu Text";
MenuText.FontSize = 20;
MenuText.FontFamily = new System.Windows.Media.FontFamily("Courier");
MenuText.Margin = new Thickness(300, 0, 0, 0);
MenuText.Foreground = this.FontColor;

MenuCount.Text = "1 of 100";
MenuCount.FontSize = 20;
MenuCount.FontFamily = new System.Windows.Media.FontFamily("Courier");
MenuCount.Margin = new Thickness(500, 0, 0, 0);
MenuCount.Foreground = this.FontColor;

MainContent = MenuText;
MainContent = MenuCount; //This is where the code is incorrect, obviously. I need to have both of these items, and two images (not in the code yet) within this.
}
[/CODE]

[CODE]
<UserControl x:Class="BediaMenu.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignHeight="55" d:DesignWidth="458">
<StackPanel HorizontalAlignment="Left" Margin="10">
<ContentControl Content="{Binding MainContent}"/>
</StackPanel>
</UserControl>
[/CODE]

Any thoughts?

4 answers to this question

Recommended Posts

  • 0

Can't you just use ContentControl.AddChild?

However, it's considered a bad idea define all markup and styles in C# code. You should make use of the true power of WPF which is its binding and template framework. Since you're only creating static content, you should be fine using a ListBox with a custom ItemTemplate and bind it to the collection to display. That way, you have a beautifully structured MVVM architecture. :)

Check out the MSDN page on ItemTemplate for a good example. You can then further style those ListBoxItems with an ItemContainerStyle.

  • 0

why code stuff in c# and not use the XAML markup?

Besides, those big margins you use.. I think you will have some big problems later when you have more stuff in your window

I have worked with VB for 18 years and C# was the logical next move. I started playing with WPF to get a handle on it's tech and I was testing some of it via code, as opposed to XAML, just to see the process.

I have changed this code to XAML using TextBlocks to display the data., but thanks for the heads up.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Could God or aliens actually be real as new theory says we shouldn't even exist by Sayan Sen Image by cottonbro studio via Pexels A study published in July 2025 examined one of science's biggest unanswered questions: how life first emerged from non-living matter on early Earth. The research, led by Robert G. Endres of Imperial College London, used mathematics to examine how difficult it would have been for the first living system, known as a protocell, to form before Darwinian evolution began. The origin of life remained an open question in physics and chemistry. Scientists had already studied how simple molecules might have formed under early Earth conditions, but this study focused on a different challenge: how those molecules could have become organized into a functioning living system. To investigate this, Endres developed a mathematical framework based on information theory and algorithmic complexity. Information theory is a branch of mathematics that studies how information is stored, measured and organized. In this study, it was used to estimate how much meaningful information a biological system would have needed to function. Algorithmic complexity measures how much information or how many instructions are required to describe or recreate something. More complex systems require more detailed organization. The study applied these ideas to a protocell, a simple cell-like structure that scientists considered a possible early step toward life. A protocell would have needed basic features, such as a boundary separating its internal chemical environment from its surroundings, before more advanced biological processes could develop. Using modern computational estimates, the research evaluated how difficult it would have been to assemble the organized biological information needed for a protocell under plausible prebiotic conditions. Prebiotic conditions referred to Earth's chemical and physical environment before life existed, including oceans, minerals and energy sources that might have supported chemical reactions. The findings suggested that forming a viable protocell would have faced major informational and physical barriers during the relatively limited time available in Earth's early history. As biological systems became more complex, the amount of organized information required also increased, making spontaneous assembly through random processes increasingly difficult. The study compared this challenge to trying to write an article about the origins of life for a well-renowned space-based website by randomly placing letters onto a page. Individual letters might have appeared by chance, but producing a complete and meaningful article became vastly less likely as more information was required. The comparison illustrated why assembling a highly organized biological system presented such a significant scientific challenge. The research also examined entropy, a concept in physics that describes the number of possible arrangements within a system and is often associated with increasing disorder. Because natural processes tend to move toward states with greater entropy, explaining how the highly organized structures found in living systems developed from non-living matter remains a major scientific challenge. The study did not conclude that life could not have originated naturally on Earth. Instead, it suggested that current scientific understanding might have been incomplete and that additional physical principles or mechanisms might have been needed to explain how biological organization first emerged. The paper stated that "Ultimately, uncovering physical principles for life's spontaneous emergence remains a grand challenge for biological physics." Biological physics is the field that applies the principles of physics to understand living systems, from molecules and cells to larger biological structures. The study also discussed directed panspermia, a speculative hypothesis suggesting that life might have been intentionally introduced to Earth by an advanced extraterrestrial civilization. Directed panspermia was originally proposed by Francis Crick and Leslie Orgel. The idea remained a possible but unconfirmed explanation and had not been supported by direct evidence. The paper stated, "While the idea of Earth being terraformed by advanced extraterrestrials might violate Occam's razor from within mainstream science, directed panspermia -- originally proposed by Francis Crick and Leslie Orgel -- remains a speculative but logically open alternative." Occam's razor is the scientific and philosophical principle that, when multiple explanations fit the available evidence, the one requiring the fewest assumptions is generally preferred. The study noted that directed panspermia introduced more assumptions than natural origin models. The research did not present directed panspermia as the preferred explanation, nor did it rule out the possibility that life emerged naturally on Earth. Instead, it measured the scale of the informational challenge and suggested that further discoveries might be needed to identify mechanisms that could explain the transition from non-living chemistry to life. Scientists continued investigating the origin of life through chemistry, biology, geology and physics. Previous research had explored environments such as hydrothermal vents, shallow pools and mineral surfaces where early chemical processes might have taken place. This study did not directly test those ideas. Instead, it examined the broader requirements that any successful explanation would have needed to meet. By combining mathematics with biology, the research aimed to provide a more quantitative way of studying the origin of life. Although it did not answer how life began, it highlighted the complexity of the problem and the need for further research into one of science's most enduring mysteries. Source: Imperial College London via Universe Today, arXiv This article was generated with some help from AI and reviewed by an editor. Under Section 107 of the Copyright Act 1976, this material is used for the purpose of news reporting. Fair use is a use permitted by copyright statute that might otherwise be infringing.
    • +-------------------------------------------------+ | HEADER (TT4 Standard) | | Menü: News | Areas | Technologies | +-------------------------------------------------+ | 🟥 HERO = NEWS | | ------------------------------------------------| | Title: "the actual news & Updates" | | | | • News 1 (newest) | | • News 2 | | • News 3 | | | | [see all news →] | +-------------------------------------------------+  
    • I was surprised too, but it was the only working one I could find at the time. BTW, Google Gemini pointed the blame at tech sites that are overzealously implementing anti-bot stuff and mistaking some RSS apps for being bots. That's consistent with the Forbidden and Access Denied responses these two RSS apps were getting. That said, I'm glad these apps are back to working with Neowin's standard Feed URLs. 
    • good day dear friends,      update: well i think that i have solved this issue - i did some investigations & experiments and finally i think i have found out a solution.  Btw: i am more  than glad to be part of this great forum. Its a big big and incredible help for me. Keep up this great place - it rocks   full story: update:  i think that this is the thing...:  the basis: in the  Twentytwentyfour-theme (TT4)  i want to have a  News-Block:  a. Block 1 (News)   which shows the latest three news - News 1 - News 2 - News 3 i guess that this is so called Query Loop Block (Posts, sort: newest, count: 3) - see here: hmm - well i guess that this is exactly a Query Loop block. Since the Twenty Twenty-Four (TT4) theme is a full-site editing (FSE) block theme, we can build this layout directly in the editor without writing any code. How to configure the block in the TT4 theme Insert the block: Add a Query Loop block into our Hero section. Settings in the right sidebar: Post Type: select Posts. Order: WordPress defaults to Newest to oldest, which matches our requirement. Count: set Items per page to exactly 3. Sticky posts: set this to Exclude so that old, pinned posts do not break your chronological order. well i think that the  structure for our layout sketch could be done like so: To match our sketch precisely, we could nest the blocks inside the editor like this so - as an example: Group (here we use this to set the background color for our red 🟥 Hero area) Heading: "the actual news & Updates" Query Loop BlockPost Template (this repeats automatically 3 times)List or Group (to achieve the bullet point • look) Post Title (linked to the single post) Buttons: "[see all news →]" (manually link this button to your main news archive page) Well i  think  that i try this out - btw: how to filter this block so it only displays a specific category (e.g., only "News" instead of general blog posts), if someone has a idea - it would be great have a great day.🤩 and keep up the great forum - a awesome place for idea-sharing and much much more👍 btw: see below a drawing of the supposed setup.
    • My experience since going cloud only is that things are easier to manage and there are less issues. Also reduced tech staff required for manage a larger amount of users / computers. My experience is that its the third party services, cloud printing etc that are behind in the reliability stakes and cause frustrations.
  • Recent Achievements

    • Rising Star
      ExPat went up a rank
      Rising Star
    • Reacting Well
      Gideon Waxfarb earned a badge
      Reacting Well
    • First Post
      NovaEdgeX earned a badge
      First Post
    • One Month Later
      pahariyaseo earned a badge
      One Month Later
    • Week One Done
      pahariyaseo earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      427
    2. 2
      PsYcHoKiLLa
      144
    3. 3
      Nick H.
      89
    4. 4
      Steven P.
      84
    5. 5
      +Edouard
      80
  • Tell a friend

    Love Neowin? Tell a friend!