Static class as resource for xaml in wpf.

huangapple go评论60阅读模式
英文:

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 = &quot;Parameter&quot;;
    }

View:

xmlns:global=&quot;clr-namespace:Project.Global&quot;

 &lt;DataGridTextColumn Header=&quot;{Binding Source={global:GlobalDefinitions,Path=Parameter}&quot;/&gt;

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:

&lt;DataGridTextColumn
    Header=&quot;{Binding Source={x:Static global:GlobalDefinitions.Parameter}}&quot;/&gt;

答案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):

&lt;Application.Resources&gt;
  &lt;ResourceDictionary&gt;
      &lt;myNamespace:MyClass x:Key=&quot;MyClass&quot; /&gt;
  &lt;/ResourceDictionary&gt;
&lt;/Application.Resources&gt;

Then you can use it as a binding source e.g.:

&lt;Window 
    DataContext=&quot;{Binding Source={StaticResource MyCLass}}&quot;
    &gt;
&lt;/Window&gt; 

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.

huangapple
  • 本文由 发表于 2023年5月25日 20:53:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定