在C#中添加Style后获取Button.Content XAML

时间:2015-11-30 09:16:13

标签: c# windows xaml win-universal-app

如果我在我的.xaml视图中声明了按钮内容,请执行以下操作:

<Button>
  <Grid>
    <TextBlock Text="Hey" />
  </Grid>
</Button>

我可以使用Button.Content在我的C#代码中轻松获取它并将其转换为Grid。

但是当我通过Code添加一个带有ControlTemplate的Style然后想要获取内容时,它总是为空...

Button btn = new Button();
btn.Style = App.Current.Resources["MyStyle"] as Style;

Grid grid = btn.Content as Grid; //<-- Always null

我的风格如下:

<Style x:Name="MyStyle" TargetType="Button">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate>
        <Grid>
          <TextBlock Text="Hey" />
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

按钮在视图中正确设置样式...

1 个答案:

答案 0 :(得分:1)

我使用以下代码获得了文本:

        Grid g = VisualTreeHelper.GetChild(btn, 0) as Grid;
        TextBlock t = g.Children[0] as TextBlock;
        string txt = t.Text;

请注意,在创建按钮后不能使用代码(我认为当时尚未应用该样式)。您可以添加另一个按钮,在点击事件中添加代码。

相关问题