C#添加Style后得到Button.Content | Xaml
Get Button.Content after Style was added in C# | Xaml
如果我在我的 .xaml 视图中声明一个按钮的内容:
<Button>
<Grid>
<TextBlock Text="Hey" />
</Grid>
</Button>
我可以使用 Button.Content 在我的 C# 代码中轻松获取它并将其转换为网格。
但是当我通过代码添加一个Style with ControlTemplate 然后想要获取内容时,它总是空...
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>
按钮在视图中的样式正确...
我使用以下代码获取了文本:
Grid g = VisualTreeHelper.GetChild(btn, 0) as Grid;
TextBlock t = g.Children[0] as TextBlock;
string txt = t.Text;
请注意,您不能在创建按钮后立即使用代码(我认为当时尚未应用样式)。可以再添加一个按钮,在点击事件中添加代码。
如果我在我的 .xaml 视图中声明一个按钮的内容:
<Button>
<Grid>
<TextBlock Text="Hey" />
</Grid>
</Button>
我可以使用 Button.Content 在我的 C# 代码中轻松获取它并将其转换为网格。
但是当我通过代码添加一个Style with ControlTemplate 然后想要获取内容时,它总是空...
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>
按钮在视图中的样式正确...
我使用以下代码获取了文本:
Grid g = VisualTreeHelper.GetChild(btn, 0) as Grid;
TextBlock t = g.Children[0] as TextBlock;
string txt = t.Text;
请注意,您不能在创建按钮后立即使用代码(我认为当时尚未应用样式)。可以再添加一个按钮,在点击事件中添加代码。