通过完全限定的对象名称而不是字符串访问资源

  • 本文关键字:字符串 资源 访问 对象 c# wpf
  • 更新时间 :
  • 英文 :


我在运行时更改控件的样式。如果用户处于"审阅模式",则假设将文本框更改为只读(从而更改文本框上影响显示的其他属性(。

假设我在应用程序资源中有一个样式。

<Style x:Key="ReadOnlyTextBoxStyle" TargetType="{x:Type TextBox}">
<Setter Property="BorderBrush" Value="Black"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Focusable" Value="False"/>
<Setter Property="Cursor" Value="Arrow"/>
<Setter Property="Background" Value="White"/>
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="TextBlock.FontWeight" Value="Bold"/>
<Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
<Setter Property="VerticalScrollBarVisibility" Value="Visible"/>
<Setter Property="TextWrapping" Value="Wrap"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True" Background="{TemplateBinding Background}">
<ScrollViewer Name="PART_ContentHost"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

我发现了几种通过字符串在代码隐藏中引用资源的方法,例如

myTextBox.Style = (Style).Resources["ReadOnlyTextBoxStyle"];

但是我找不到通过这样的东西访问资源的示例:

myControl.Style = (Style).Resources[nameOf(IsThere.Some.Way.To.Get.QualifiedReferenceToStyleResourceKey)];

如果我使用类似的东西:

myControl.Style = (Style).Resources["ReadOnlyTextBoxStyle"];

然后我将键更新为一个新字符串,例如"ReadOnlyTextBoxStyleModified",然后我必须在代码中引用它的任何地方更改它。如果我错过了其中一个替换,直到运行时我才会收到错误。如果可能的话,我更愿意在编译时看到错误。

下面链接的问题中的答案建议使用命名常量,但没有提供示例。这似乎可以实现我想要的目标,但我不明白如何实现他的评论,他说

"此外,一个好的做法是创建一个字符串常量,该常量在资源字典中映射您的密钥名称(这样您只能在一个地方更改它(。

通过 WPF 中的代码隐藏访问资源

您可以为资源键创建一个具有静态字符串成员的类,例如

public static class ResourceKeys
{
public static string Key1 = "Key1";
}

然后使用这样的键声明资源,例如

<Window.Resources>
<SolidColorBrush x:Key="{x:Static local:ResourceKeys.Key1}" Color="Red"/>
</Window.Resources>

并按其键使用该资源,例如

<Grid Background="{StaticResource ResourceKey={x:Static local:ResourceKeys.Key1}}">

或喜欢

grid.Background = (Brush)FindResource(ResourceKeys.Key1);

最新更新