简体   繁体   中英

Adding button to the user control using class method in Windows Phone 7

I am developing a user control for WP7 application. I added the control to MainPage.xaml and I want the control to create the button from a class called MyButton using the method Add_button_internal() , but I can't to figure out how to do it.

When I try to use a method Add_button_external(); which is outside the class MyButton , there is no problem.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;


namespace PhoneApp4
{
    public partial class WindowsPhoneControl1 : UserControl
    {
        public WindowsPhoneControl1()
        {
            InitializeComponent();

            // THIS WORKS FINE
            LayoutRoot.Children.Add(Add_button_external("button name"));

            // THIS DOESNT WORK :(
            MyButton t = new MyButton();
            t.Add_button_internal("button name");
        }

        public Button Add_button_external(string m)
        {
            Button btn = new Button();
            btn.Content = m;
            return btn;  
        }

        public class MyButton
        {
            public MyButton() { }

            public Button Add_button_internal(string n)
            {
                Button btn = new Button();
                btn.Content = n;
                return btn;                    
            }
        }
    }
}

Can you please help me to solve my problem?

Your MyButton classes Add_Button_Internal method only returns a newly created button, you would have to add it to the layoutroot.childer collection to display it on the UI. So i think your problem is only that you forget to add the new button to the UI.

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