繁体   English   中英

从用户控件内访问 MainWindow 中的用户控件名称

[英]Access user control name in MainWindow from within user control

我似乎无法从该用户控件中访问我在MainWindow.xaml的用户控件上设置的x:Name属性。

this.Name属性是空的! 可能,这不是我正在寻找的属性( 为什么我不能在同一个程序集中使用 UserControl 上的 Name 属性? )。

我尝试在标准InitializeComponent();之后立即在虚拟线上放置调试停止InitializeComponent(); UserControl1()构造函数中,并挖掘各种基类中的属性,但没有找到任何与x:Name相似的内容。

我的 MainWindow.xaml 看起来像这样:

  <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>

这是我的 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>

UserControl1.cs 中的代码:

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

标签应该设置为“label: sup”,但是 this.name 是空的,所以它只是标签。

如果向用户控件添加按钮,则在调用构造函数后应用 x:Name 属性

<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>

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

这应该使用主窗口中提供的名称更新标签。

要在没有交互的情况下进行更新,请将其添加到用户控件定义中

Loaded="UserControl1_OnLoaded"

在代码隐藏中

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM