O
O
Ogoun Er2011-05-17 17:13:13
Batteries
Ogoun Er, 2011-05-17 17:13:13

WPF. Creating elements from code

I made my own base class for subsequent inheritance of windows from it. Everything works, but now I want controls to be created in it, i.e. so that the heirs already have, for example, StackPanel. When creating a base window class, you cannot use XAML, that is, the creation of an element must be written in code. How can it be implemented?
An example for clarity:

public partial class BaseToolPanel : Window
  {
    StackPanel stackPanel=new StackPanel();
    public BaseToolPanel()
    {
      stackPanel.Background=Brushes.Red;
      stackPanel.Name="spVidgets";
      //Делаю так, не отображается
      base.AddChild(stackPanel);
      base.AddVisualChild(stackPanel);
      base.AddLogicalChild(stackPanel);
    }
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
kefirr, 2011-05-17
@kefirr

All those Add* methods are for other things, you don't need them.
Window is a ContentControl. It has a Content property, into which the content is set. Content is one object. Be it Grid, StackPanel, whatever. Therefore, just adding something so that the heirs already have it will not work.
The problem is solved using the ContentProperty attribute, which redirects the so-called. Direct Content (what is set in xaml) to the specified property.
In short, here is the working code:

  [ContentProperty("Child")]
  public class BaseWindow : Window
  {
   #region Fields and Constants
   public static readonly DependencyProperty ChildProperty =
     DependencyProperty.Register("Child", typeof (object), typeof (BaseWindow), new UIPropertyMetadata(0));
   #endregion
   #region Constructors
   public BaseWindow()
   {
     var rootStackPanel = new StackPanel();
     rootStackPanel.Children.Add(new Button {Content = "I'm button from base class"});
     var childContentControl = new ContentControl {DataContext = this};
     childContentControl.SetBinding(ContentProperty, "Child");
     rootStackPanel.Children.Add(childContentControl);
     Content = rootStackPanel;
   }
   #endregion
   #region Public properties and indexers
   public object Child
   {
     get { return GetValue(ChildProperty); }
     set { SetValue(ChildProperty, value); }
   }
   #endregion
  }
* This source code was highlighted with Source Code Highlighter.

A
Alexander Vishnyakov, 2013-11-19
@asvishnyakov

Why not use XAML? Why such an idiotic limitation?
This is usually solved by using the Style / Control Template + overriding ApplyTemplate, if you need, for example, to subscribe to events on the control.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question