以编程方式设置TextBlock的样式

11

我有这个:

var MyText = new TextBlock();
MyText.Text = "blah";
MyText.Style = /* ??? */;
在XAML中,我可以像这样设置样式:
<TextBlock Text="blah" Style="{ThemeResource ListViewItemTextBlockStyle}"/>

但是我如何在C#中实现呢?

编辑:

Error   1   'Windows.UI.Xaml.Application' does not contain a definition for 'FindResource' and no extension method 'FindResource' accepting a first argument of type 'Windows.UI.Xaml.Application' could be found (are you missing a using directive or an assembly reference?)
Error   1   'Geodropper.HubPage' does not contain a definition for 'FindResource' and no extension method 'FindResource' accepting a first argument of type 'Geodropper.HubPage' could be found (are you missing a using directive or an assembly reference?)

当我尝试使用(Style)this.FindResource("ListViewItemTextBlockStyle");(Style)App.Current.FindResource("ListViewItemTextBlockStyle")时,出现了以下错误。


1
MyText.Style = (Style)this.FindResource("ListViewItemTextBlockStyle"); 这里的 this 指的是包含资源的窗口或元素,也可以使用 (Style)App.Current.FindResource("ListViewItemTextBlockStyle") - Xi Sigma
https://dev59.com/aHI-5IYBdhLWcg3wsKh4 和 https://dev59.com/fmgv5IYBdhLWcg3wTvPL - Eugene Podskal
@decoherence 对我来说,这两个都没有起作用。 - user3745735
1
@ZudoMC 抱歉,我以为你在使用 WPF,否则可以使用 (Style)App.Current.Resources["ListViewItemTextBlockStyle"] 或者 (Style)this.Resources["ListViewItemTextBlockStyle"] - Xi Sigma
@decoherence 谢谢,那个有效! - Zudo
1个回答

17

谢谢decoherence!我所需要的是以下内容:

var MyText = new TextBlock();
MyText.Text = drop;
MyText.Style = (Style)Application.Current.Resources["ListViewItemTextBlockStyle"];

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接