我有这个:
var MyText = new TextBlock();
MyText.Text = "blah";
MyText.Style = /* ??? */;
Run Code Online (Sandbox Code Playgroud)
在XAML中,我可以设置这样的样式:
<TextBlock Text="blah" Style="{ThemeResource ListViewItemTextBlockStyle}"/>
Run Code Online (Sandbox Code Playgroud)
但是我如何在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 …Run Code Online (Sandbox Code Playgroud) 所以,我正在使用C#中的WPF创建一个GUI.它看起来像这样:

它现在还没有完成.这两行是我尝试制作一种数据表,它们在XAML中是硬编码的.
现在,我正在C#中实现添加新的水果按钮功能.我在XAML中有以下样式来控制行的背景图像应该是什么样子:
<Style x:Key="stretchImage" TargetType="{x:Type Image}">
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Stretch" Value="Fill"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
因此,在代码中,我为每列创建一个图像,col0,col1,和col2,如果我使用下面的代码,
col0.Style = (Style)Application.Current.Resources["stretchImage"];
col1.Style = (Style)Application.Current.Resources["stretchImage"];
col2.Style = (Style)Application.Current.Resources["stretchImage"];
Run Code Online (Sandbox Code Playgroud)
它添加了一个如下所示的新行:

正如你所看到的,它不太正确......而拉伸窗口会加剧问题:

它似乎不尊重风格的"Stretch"属性.
但是,如果我改为将样式加载代码改为
col0.Style = (Style)FindResource("stretchImage");
col1.Style = (Style)FindResource("stretchImage");
col2.Style = (Style)FindResource("stretchImage");
Run Code Online (Sandbox Code Playgroud)
它工作得很漂亮:

(同样,应用程序还没有完成,所以不要担心),但我的主要问题是:Application.Current.Resources[]和之间有什么区别FindResource()?为什么一个似乎忽略了一些属性而另一个没有?如果可能的话,我可以Application.Current.Resources[]如何正常工作?
我正在尝试将我的 xaml 样式之一设置为页面中的框架。它是在代码中创建的,并动态分配给布局。
所以我希望我必须动态设置样式?因为 xaml 中不存在该框架。
我不明白的是如何分配自定义模板。或者更好的是,以全局方式处理适合特定类别的任何框架。标记或键入等。
下面是我尝试测试的模板。但这不起作用。假设代码丢失,因此开始检查代码隐藏样式设置,但到目前为止还没有运气。
应用程序.xaml
<!-- http://paulstovell.com/blog/wpf-navigation -->
<ControlTemplate TargetType="Frame" x:Key="frame" >
<DockPanel Margin="7">
<StackPanel
Margin="7"
Orientation="Horizontal"
DockPanel.Dock="Top"
>
<Button
Content="Avast! Go back!"
Command="{x:Static NavigationCommands.BrowseBack}"
IsEnabled="{TemplateBinding CanGoBack}"
/>
<Button
Content="Forward you dogs!"
Command="{x:Static NavigationCommands.BrowseForward}"
IsEnabled="{TemplateBinding CanGoForward}"
/>
</StackPanel>
<Border
BorderBrush="Green"
Margin="7"
BorderThickness="7"
Padding="7"
CornerRadius="7"
Background="White"
>
<ContentPresenter />
</Border>
</DockPanel>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)
MyWindow.xaml.cs
Frame newFrame = new Frame();
newFrame.Content = content;
newFrame.Template = ControlTemplate ...?
Run Code Online (Sandbox Code Playgroud)