简体   繁体   中英

How to access an element in UserControl from the MainPage?

I have a UserControl that is an ItemTemplate for a FlipView that exists in my MainPage. This UserControl contains a Canvas which name is x:Name="InkCanvas" .

And I want to initialise this Canvas and access it from my MainPage.xaml.cs :

private readonly CanvasManager m_CanvasManager;
m_CanvasManager = new CanvasManager(InkCanvas);

Setting it to static couldn't help! How can it be possible?

Try this:

private readonly CanvasManager m_CanvasManager;
this.InkCanvas = new CanvasManager();
m_CanvasManager = this.InkCanvas;

You can add to your UserControl.cs this method:

public Canvas GetInkCanvas()
{
   return InkCanvas;
}

And use it form MainPage.cs :

var canvas = userControl.GetInkCanvas(); // userControl - here is the instanse of UserControl.

But in general - this is not a good idea to share your Canvas from your UserControl .

What I understand is: Your user control is an item template for a FlipView, and you can't find way to access its content, so, what you need is:

(yourFlipView.Items[index] as YourUserControl).getCanvas();

The getCanvas() is the getter of the canvas you want to access in your user control, you have to implement it in YourUserControl.cs

事实证明,如果此UserControl不是我当前的ItemTemplate :我将无法访问其任何控件。

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