获取按钮.在C#| Xaml中添加样式后的内容

本文关键字:样式 添加 按钮 Xaml 获取 | 更新日期: 2023-09-27 18:25:11

如果我在.xaml视图中声明按钮的内容,如下所示:

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

我可以很容易地在我的C#代码中使用Button.Content获得它,并将其转换为网格。

但是,当我通过代码添加带有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>

按钮在视图中的样式正确。。。

获取按钮.在C#| Xaml中添加样式后的内容

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

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

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