英文:
Static class as resource for xaml in wpf
问题
I try to use a static class as ResourceDirectory with StaticResources but it dont works.
Class:
static class GlobalDefinitions
{
public const string Parameter = "Parameter";
}
View:
xmlns:global="clr-namespace:Project.Global"
<DataGridTextColumn Header="{Binding Source={x:Static global:GlobalDefinitions.Parameter}}"/>
Does anyone know why?
英文:
I try to use a static class as ResourceDirectory with StaticResources but it dont works.
Class:
static class GlobalDefinitions
{
public const string Parameter = "Parameter";
}
View:
xmlns:global="clr-namespace:Project.Global"
<DataGridTextColumn Header="{Binding Source={global:GlobalDefinitions,Path=Parameter}"/>
Does anyone know why?
I try to use a static class as ResourceDirectory with StaticResources but it dont works.
答案1
得分: 1
使用x:Static
标记扩展:
<DataGridTextColumn
Header="{Binding Source={x:Static global:GlobalDefinitions.Parameter}}"/>
英文:
Use the x:Static
markup extension:
<DataGridTextColumn
Header="{Binding Source={x:Static global:GlobalDefinitions.Parameter}}"/>
答案2
得分: -2
我通常会将我的类声明为资源...
给定一个类:
public class MyClass
{
//
}
声明资源(在App.xaml中的示例):
<Application.Resources>
<ResourceDictionary>
<myNamespace:MyClass x:Key="MyClass" />
</ResourceDictionary>
</Application.Resources>
然后你可以将它用作绑定源,例如:
<Window
DataContext="{Binding Source={StaticResource MyClass}}"
>
</Window>
WPF会根据需要创建类的实例以解析绑定。为了使这种方法生效,该类必须具有无参数的构造函数。
“Locator”模式的类似方式运作;你可以拥有底层的静态成员,但它们需要被实例成员包装。
英文:
I will typically declare my class as a resource...
Given a class:
public class MyClass
{
//
}
Declare the resource (this is how it would look in App.xaml):
<Application.Resources>
<ResourceDictionary>
<myNamespace:MyClass x:Key="MyClass" />
</ResourceDictionary>
</Application.Resources>
Then you can use it as a binding source e.g.:
<Window
DataContext="{Binding Source={StaticResource MyCLass}}"
>
</Window>
WPF will create an instance of the class as needed to resolve the binding. For this approach to work, the class must have a parameterless constructor.
The class "Locator" pattern works this way; you could have underlying static members, but they would need to be wrapped by instance members.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论