user4134476
user4134476

Reputation: 385

How to use a public method in a custom control without using x:Name

I have my custom control MyControl, which has a public method Start().

public partial class MyControl : UserControl
{
    // This must be private.
    private int _idNumber;

    public MyControl()
    {
        InitializeComponent();
    }

    public void Start(int idNumber)
    {
        _idNumber = idNumber;
    }
}

In the MainWindow, I put one MyControl with x:Name="myControl".

<Window x:Class="MyNameSpace.MainWindow"
        xmlns:local="clr-namespace:MyNameSpace">
    <Grid>
        <local:MyControl x:Name="myControl"/>
    </Grid>
</Window>

In the Start method of the MainWindow, I call the Start method of MyControl using x:Name.

public partial class MainWindow : Window
{
    // This must be private
    private int _myContolId;

    public MainWindow()
    {
        InitializeComponent();
    }

    public void Start()
    {
        // ID must be set here.
        _myControlId = 1;
        myControl.Start(_myControlId);
    }
}

How can I do the same thing without using x:Name?

Note that Loaded event of MyControl is ineffective in my case, since the Start() method of MyControl MUST be called before it is loaded as a visual element.

It is also ineffective to call Start in the constructor of MyControl or when it is initialized, since the int argument idNumber must be set in the Start method of MainWindow.

What is more, both _idNumber of MyControl and _myContolId of MainWindow must be private, for both setter and getter.

Upvotes: 1

Views: 89

Answers (1)

AnjumSKhan
AnjumSKhan

Reputation: 9827

Handle Initialized event of your UserControl. <local:MyControl x:Name="myControl" Initialized="myControl_Initialized"/>

Whether you choose to handle Loaded or Initialized depends on your requirements. If you do not need to read element properties, intend to reset properties, and do not need any layout information, Initialized might be the better event to act upon. If you need all properties of the element to be available, and you will be setting properties that are likely to reset the layout, Loaded might be the better event to act upon.

Source : FrameworkElement.Initialized Event

You should create the UserControl in code like below and add it :

 public partial class MainWindow : Window
 {
// This must be private
private int _myContolId;

public MainWindow()
{
    InitializeComponent();
}

public void Start()
{
    // ID must be set here.
    _myControlId = 1;
    MyControl myControl = new MyControl();
    myControl.Start(_myControlId);

    GridContainer.Children.Add(myControl);
}

}

This will solve your problem. If you declare an element/control XAML, then it will be created as XAML file is parsed.

Upvotes: 1

Related Questions