0

I would like to add dinamically UIElement through ICommand. It is working fine with EventHandler but when I try to do the same using ICommand the UIElement is invisible however it seams the stackpanel contains it because the 'Capacity' and 'Count' is 1 after the addition.

The ICommand (AddElement) can be found within the ViewModel and The EventHandler can be found within the MainWindow.

I made a comparison. Can you please check it what is still missing? If the provided information is not enough please let me know. Many Thanks in advance!

public void AddElement(StackPanel sp)
    {
        Button btn = new Button()
        {
            Content = "TestButton",
            Height = 20,
            Width = 20,
        };
       sp.Children.Add(btn);
    }

public void AddElem(object msg)
    {
        MainWindow mw = new MainWindow();
        mw.Owner = System.Windows.Application.Current.MainWindow;
        _actions.AddElement(mw.TestStack);
    }


private void BtnAddList_Click(object sender, RoutedEventArgs e)
    {
        Button btn = new Button()
        {
            Content = "TestButton",
            Height = 20,
            Width = 20,
        };
        TestStack.Children.Add(btn);
    }
Milán
  • 1
  • 1
  • AddElem creates a second instance of MainWindow. I'm quite sure this is not what you intended. – Klaus Gütter Mar 07 '21 at 15:28
  • At the first time I could not find other way to add the UIElement to the stackpanel on the MainWindow. I am a quite new in C# but now I found the following opporutnity: _actions.AddElement(((MainWindow)Application.Current.MainWindow).TestStack); and with this it is working. I am sure there is a more sophisticated solution but for me it will be fine. Thank you for the comment! – – Milán Mar 07 '21 at 17:41

0 Answers0