简体   繁体   中英

How to insert button into Grid from ViewModel C# class in windows 8.1 store app

I can insert button to a grid control from the code behind file as

var fElem = new Button();                 

fElem.Content = "button text";
bgGrid.Children.Add(fElem); // bgGrid defined in xaml

How can I add the same button to the grid from the view model class?

In code-behind of the xaml page (xaml.cs) you need to publicly expose the grid

public Grid MyGrid => bgGrid;

Then you can get access to it from your ViewModel like so:

Frame rootFrame = Window.Current.Content as Frame;
var page = rootFrame.Content as YourPageClassName;
var fElem = new Button();                 
fElem.Content = "button text";
page.MyGrid.Children.Add(fElem); 

However, this is not MVVM at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM