【问题标题】:changing custom control textblock value by code通过代码更改自定义控件文本块值
【发布时间】:2013-02-21 21:24:43
【问题描述】:

我正在学习如何编写 Windows 8 应用程序,但我找不到任何问题的答案。

我创建了一个自定义控件,通过单击按钮添加:

onclick() {
    card currentcard = new card();
    ...
    ...
    hand.Children.add(currentCard);
}

在 page.cs 中

当前卡片控件有 Generic.xaml 信息,看起来像这样,其中包含 TextBlock

<Style TargetType="local:tile">
  <Setter Property="VerticalAlignment" Value="Center"/>
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="local:tile">
        <Border
             Background="{TemplateBinding Background}"
             BorderBrush="{TemplateBinding BorderBrush}"
             BorderThickness="{TemplateBinding BorderThickness}">
          <TextBlock x:Name="Label"/> // <----------------------- this textblock
        </Border>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

我可以在 page.cs 或 card.cs 中做什么来获取/设置名为 Label 的 TextBlock 的值?

对不起,如果这是基本的或以前在某个地方回答过,我进行了搜索,但没有找到答案!

【问题讨论】:

标签: c# xaml windows-store-apps controltemplate


【解决方案1】:

因为有问题的 TextBlock 是称为 Tile 的自定义类型的 ControlTemplate 的一部分,所以最好的办法是将 DependencyProperty 添加到 Tile 类型并使用 TemplateBinding 绑定将TextBlockText 属性转换为这个新DependencyProperty 的值。

您不能轻易地从外部访问ControlTemplate 来修改该模板的一部分的值。

This answer 提供了一个使用DependencyProperty 并将其绑定到ControlTemplate 的示例,快速搜索可能会产生许多其他示例。

【讨论】:

  • 哦,谢谢,我会调查的。抱歉,如果我知道 DependencyProperty,我会查一下的。感谢您帮我解决这个问题!
  • 很高兴为您提供帮助。 Here 是关于 DependencyProperties 的 MSDN 文章。如果您觉得这回答了您的问题,请将其标记为答案。
猜你喜欢
  • 2015-07-11
  • 2012-04-07
  • 2012-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
相关资源
最近更新 更多