【问题标题】:Can't access child element in UserControl无法访问 UserControl 中的子元素
【发布时间】:2013-04-23 12:38:17
【问题描述】:

我创建了一个带有 TextBlock 的 UserControl,问题是我无法从使用此 UserControl 的 MainPage 更改此 UserControl 的文本。

请帮助我是 Metro 风格应用程序的新手,基本上是 windows 手机开发人员。检查下面的用户控件的来源。

<UserControl
x:Class="Version1forMainMenu.MyUserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Version1forMainMenu"
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" x:Name="MyUserControl1">

<Grid x:Name="grid_amorti"  PointerEntered="gride_quickestimate_PointerEntered" PointerExited="gride_quickestimate_PointerExited" PointerPressed="gride_quickestimate_PointerPressed" PointerReleased="gride_quickestimate_PointerReleased" Tapped="gride_quickestimate_Tapped">
    <Grid.Background>
        <ImageBrush ImageSource="Image/inside_menu_normal.png"/>            
    </Grid.Background>


    <TextBlock Grid.Row="1" Grid.Column="2" Grid.ColumnSpan="3"  x:Name="edit"   Text="" FontSize="30" FontWeight="Bold" VerticalAlignment="Center" FontFamily="Global User Interface" Margin="10,112,29,111" ></TextBlock>
    <Image Grid.Row="1" x:Name="img" Grid.Column="5" Source="Image/small_arrow.png"  />


</Grid>

我无法从使用此 UserControl 的页面访问名为“edit”的文本块。

【问题讨论】:

  • 为什么不使用x:FieldModifier Directive
  • 那不是很干净,控件的名称不是外部元素应该知道的。 IMO 最好的方法是公开有用的属性,就像普通控件一样。此外,它还允许您在声明和使用 UserControl 时对这些属性进行数据绑定。

标签: c# xaml microsoft-metro


【解决方案1】:

正常,TextBlock 是 UserControl 内部的私有字段。您需要重新公开您希望能够修改的属性,例如使用这种技术:http://www.geekchamp.com/tips/how-to-expose-properties-of-a-user-control-in-windows-phone

【讨论】:

    【解决方案2】:

    这是完全正常的,因为您在用户控件中的控件不可公开访问。您应该在用户控件中定义一个公共属性以使这些控件可用...

    【讨论】:

    • 如何为在 XAML 中创建的控件定义公共属性。
    • @GY1 这是一个非常好的问题,可惜我无法回答 :-)
    【解决方案3】:

    您好像缺少Grid.ColumnDefinitions 和Grid.RowDefinitions

    <Grid x:Name="grid_amorti" ...>  
        <Grid.Background>
             <ImageBrush ImageSource="Image/inside_menu_normal.png"/>            
        </Grid.Background>
        <Grid.ColumnDefintion>
    
        </Grid.ColumnDefinition>
        <Grid.RowDefiniton>
    
        </Grid.RowDefinition>
    </Grid>
    

    所以你实际上放错了它们......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 2016-05-03
      • 2012-09-09
      • 1970-01-01
      相关资源
      最近更新 更多