简体   繁体   中英

Access user control name in MainWindow from within user control

I can't seem to be able to access the x:Name property that I set on a user control in my MainWindow.xaml , from within that user control.

The this.Name property is empty! Probably, this isn't the property I'm looking for ( Why can't I use the Name attribute on UserControl in the same assembly? ).

I tried placing a debug stop on a dummy line right after the standard InitializeComponent(); in the UserControl1() constructor, and dig through the properties in the various base classes, but haven't found anything that resemebles x:Name .

My MainWindow.xaml looks like this:

  <Window x:Class="UserControlName.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:xw="clr-namespace:UserControlName"

          Title="MainWindow" Height="350" Width="525">
      <Grid>
          <xw:UserControl1 x:Name="sup" />
      </Grid>
  </Window>

And this is my UserControl1.xaml:

<UserControl x:Class="UserControlName.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Label x:Name="sup" Content="Label" HorizontalAlignment="Left" Margin="134,146,0,0" VerticalAlignment="Top"/>

    </Grid>
</UserControl>

And the code inside UserControl1.cs:

    public UserControl1()
    {
        InitializeComponent();
        this.sup.Content = "label: " + this.Name;
    }

The label should be set to "label: sup", but this.name is empty, so it's just label.

The x:Name attribute is applied after the constructor has been called, if you add a button to the user control

<StackPanel>
    <Label x:Name="sup" Content="Label" HorizontalAlignment="Left" Margin="134,146,0,0" VerticalAlignment="Top"/>

    <Button Height="25" Width="100" Click="ButtonBase_OnClick"></Button>
</StackPanel>

And

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
    this.sup.Content = "label: " + this.Name;
}

This should update the label with the name provided in the mainwindow.

To get this updated without a interaction, add this to the usercontrol definition

Loaded="UserControl1_OnLoaded"

And in codebehind

private void UserControl1_OnLoaded(object sender, RoutedEventArgs e)
{
    this.sup.Content = "label: " + this.Name;
}

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