Never
Never

Reputation: 323

How to add new grid into grid in code with MVVM

How can I add dynamically a grid into another grid? I can't do this:

myGrid.Children.Add(dg);

Because I don't have the instance of this grid - I'm using MVVM.

Please Help.

Upvotes: 1

Views: 1124

Answers (2)

Magnus Johansson
Magnus Johansson

Reputation: 28325

I assume, since you mention MVVM, that you want to accomplish this from your View Model?

In that case my suggestion is to send a message from the View Model to the View. In the View you add a subscription to this message and add the Grid from there.

You could do it something like this, in its most simple form. This would be using the excellent MVVM Light framework:

ViewModel.cs:

private void CreateGrid()
{
  Messenger.Default.Send<NotificationMessage>(new NotificationMessage("CreateGrid"));
}

View.xaml.cs:

Messenger.Default.Register<NotificationMessage>(this, nm =>
{
  if (nm.Notification != "CreateGrid") return;
  // Create grid here
});

Upvotes: 2

Robaticus
Robaticus

Reputation: 23157

If you're dynamically adding controls at runtime, the short answer is that you probably aren't going to be successful doing that via MVVM. Dropping that into the codebehind may be your best bet-- without knowing what kind of app you're building, it is hard to pass judgement and demand loudly that you MUST use MVVM.

That being said, I rarely find myself in a situation with WPF where I have to do dynamic control manipulation like that. Instead, I wind up using different WPF constructs (ListBox, ContentControl, ItemsControl, etc.), along with things like ItemTemplates to get what I want.

Again, without knowing more about what you're trying to accomplish, it's difficult to give any kind of prescriptive guidance.

Upvotes: 1

Related Questions