ran*_*nce 62 c# wpf resources xaml code-behind
我在我的窗口资源中定义了一个自定义集合,如下所示(在Sketchflow应用程序中,因此窗口实际上是一个UserControl):
<UserControl.Resources>
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</UserControl.Resources>
Run Code Online (Sandbox Code Playgroud)
我希望能够在代码隐藏中引用这个集合,我期望它是由x:Name,但我似乎无法访问它.
我可以使用它来获取它的引用
myRef = (MyCollection) this.FindName("myKey");
Run Code Online (Sandbox Code Playgroud)
但这似乎是hackish.这是不好的做法,还有什么会更好?谢谢 :)
jap*_*apf 71
你应该使用System.Windows.Controls.UserControl's' FindResource()或TryFindResource()方法.
此外,一个好的做法是创建一个字符串常量,它映射在资源字典的键的名称(这样就可以只在一个地方进行更改).
its*_*sho 18
不完全直接的回答,但强烈相关:
如果资源位于不同的文件中 - 例如ResourceDictionary.xaml
你可以简单地添加x:Class到它:
<ResourceDictionary x:Class="Namespace.NewClassName"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<ds:MyCollection x:Key="myKey" x:Name="myName" />
</ResourceDictionary>
Run Code Online (Sandbox Code Playgroud)
然后在代码后面使用它:
var res = new Namespace.NewClassName();
var col = res["myKey"];
Run Code Online (Sandbox Code Playgroud)
R. *_*eev 10
如果您想从其他类访问资源(不是 xaml 代码隐藏),您可以使用
Application.Current.Resources["resourceName"];
Run Code Online (Sandbox Code Playgroud)
来自System.Windows命名空间。
您可以使用这样的资源键:
<UserControl.Resources>
<SolidColorBrush x:Key="{x:Static local:Foo.MyKey}">Blue</SolidColorBrush>
</UserControl.Resources>
<Grid Background="{StaticResource {x:Static local:Foo.MyKey}}" />
Run Code Online (Sandbox Code Playgroud)
public partial class Foo : UserControl
{
public Foo()
{
InitializeComponent();
var brush = (SolidColorBrush)FindResource(MyKey);
}
public static ResourceKey MyKey { get; } = CreateResourceKey();
private static ComponentResourceKey CreateResourceKey([CallerMemberName] string caller = null)
{
return new ComponentResourceKey(typeof(Foo), caller); ;
}
}
Run Code Online (Sandbox Code Playgroud)