Saeid
Saeid

Reputation: 693

How run a method inside a wpf user control (something.xaml.cs) from another class?

Say you have a user control in which there is method which resets the form:

public void myReset()
{
   text1.Text="";
   text2.Text="";
}

And now I want to call this myReset() method from a method in a clsMyClass

    class clsMyclass
    {

        public clsMyClass()
        {
        }
        // ==================== Methods  =================
        public double SomeMethod(double Val)
        {
            UserControlRef.myReset();
            //Do things...
        }
   }

I don't know how to create a ref to the User Control. I have seen a code using Revit Extension works this way. I have done a lot of searches to figure this out but I couldn't find the right way.

Upvotes: 0

Views: 1035

Answers (2)

Zwan
Zwan

Reputation: 642

according with @StijnvanGaal its not realy good methode anyway you can retrieve any UserControl and what is in. Here a sample let say your usercontrol is in grid2 you can access it this way.

 int ChildNumber = VisualTreeHelper.GetChildrenCount(grid2);
            for (int i = 0; i < ChildNumber; i++)
            {
                Control v = (Control)VisualTreeHelper.GetChild(grid2, i);

                if (v.GetType().ToString() == "Project_wpf.UserControlRef")
                {
                    UserControlRef CM = v as UserControlRef;
                    Console.WriteLine(CM.Name); //you can check his name here
                    CM.myReset();

                }
            }

basicaly this will active your MyReset() methode in all Usercontrole of type "Project_wpf.UserControlRef" who are child of Grid2

Upvotes: 1

ProgrammingDude
ProgrammingDude

Reputation: 597

You should be able to set the x:Name attribute in xaml: x:Name="control" This will give your instance a variable name. Then in code you can refer to the instance as the name you gave it. such as control.myReset();

Upvotes: 1

Related Questions