wpf pro pls
wpf pro pls

Reputation: 87

WPF static property binding not working on a list view

I'm currently binding a list view to a list of objects and everytrhing is working.

I can bind fine to my code behind of the xaml as long as I put in my Window element DataContext="{Binding RelativeSource={RelativeSource Self}}"

My ListView looks like this and bindings work correctly for my binded columns to the properties of the items of MyCollection.

<ListView ItemsSource="{Binding MyCollection}">

For one of the columns though I always want it to say the same thing. For example this column would always contain "Hello World"

The following code gives me an error for binding:

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static Member=MyNamespace.MyStaticClass},Path=MyStaticStringField}" />

I get the error:

error MC3050: Cannot find the type 'MyNamespace'. Note that type names are case sensitive.

MyNamespace is the same namespace as the window itself and MyStaticClass is public

If I try instead:

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static Member=MyStaticClass},Path=MyStaticStringField}" />

I get the error:

error MC3029: 'MyStaticClass' member is not valid because it does not have a qualifying type name.

Strangely enough, when I do this it works:

<GridViewColumn Header="This works" DisplayMemberBinding="{Binding Source={x:Static Member=SystemFonts.IconFontFamily}, Path=Source}" />

The code for the field I'm trying to bind to:

namespace MyNamespace
{
    public static class MyStaticClass
    {
        public static string MyStaticStringField{ get; set; }

    }
}

Upvotes: 5

Views: 8249

Answers (4)

Pavlo Glazkov
Pavlo Glazkov

Reputation: 20756

With x:Static you need to specify a path to a static field or property (not just class).

<GridViewColumn Header="I want all fields to be Hello World" DisplayMemberBinding="{Binding Source={x:Static MyNamespace:MyStaticClass.MyStaticStringField}}" />

Also note that the namespace is separated from class name with colon (not dot).

Upvotes: 6

Snowbear
Snowbear

Reputation: 17274

Also adding to other answers x:static should be bound to static class MEMBER, not the class itself.

Upvotes: 0

mdm20
mdm20

Reputation: 4563

I think you have to include the namespace

xmlns:local="clr-namespace:MyNamespace"

and then use it like this:

{x:Static Member=local:MyStaticClass}

Upvotes: 4

fixagon
fixagon

Reputation: 5566

You can not bind directly to a class including the Namespace

set the NameSpace in the Page or Window or Usercontrol Declaration with xmlns:mynamespace="pathtoyournamespace"

and reference it in the binding like that: {x:Static mynamespace:MyStaticClass}, Path....

Upvotes: 2

Related Questions