按代码更改自定义控件文本块值

时间:2013-02-21 21:24:44

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

我正在学习如何编写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中获取/设置TextBlock名为Label的值吗?

对不起,如果这是基本的或以前回答的地方,我做了搜索,但我找不到答案!

1 个答案:

答案 0 :(得分:0)

因为有问题的TextBlockControlTemplate的一部分,对于名为Tile的自定义类型,您最好的选择是在您的平铺类型中添加DependencyProperty并使用TemplateBindingText的{​​{1}}属性绑定到此新TextBlock的值。

您无法轻易从外部进入DependencyProperty以修改该模板的某个部分的值。

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