locked
Accessing User Control Properties

    Question

  • Hi, I have created a UserControl as follows:

    <UserControl
        x:Class="MySample.MyControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:MySample"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        d:DesignHeight="300"
        d:DesignWidth="400">
    
        <Canvas>
            
            <Ellipse Width="150" Height="150"/>
                        
            <TextBlock>Sample</TextBlock>
    
        </Canvas>
    
    </UserControl>

    In my main page I instantiate it as follows:

    <local:MyControl x:Name="MyControl" Margin="100,50 0,0"></local:MyControl>
    Now, I would like to change the text of my Control to "Hello World". In the ctor of MainPage I tried:

    MainPage::MainPage()
    {
    	InitializeComponent();
    
    MyControl->Text = "Hello World";
    }
    But MyControl does not seem to be recognized here. Any idea ?

    Tuesday, April 03, 2012 3:17 AM

Answers

  • Hello,

    First, You should assign a x:name for the TextBlock like:
     <TextBlock x:Name="TxtBlock"   />

    Second, include your MyControl.xaml.h into your main page .cpp file.

    Last, get the text through FindName API like this:

    TextBlock^ tb=(TextBlock^)MyHelloWorldUserControl->FindName("TxtBlock");
    tb->Text="Hello";

    Best regards,
    Jesse


    Jesse Jiang [MSFT]
    MSDN Community Support | Feedback to us

    Wednesday, April 04, 2012 6:09 AM