Joan Venge
Joan Venge

Reputation: 331450

How to data bind to a static property on a non-static class?

In my ViewModel class I have a static property AllSupport but I can't figure out how to bind it correctly. The ListView is already binded to an ObservableCollection AllEffects that has the AllSupport static property.

I used this:

<GridViewColumn
    Width="Auto"
    Header="GPU">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <CheckBox
                Margin="0"
                HorizontalAlignment="Center"
                IsChecked="{Binding AllSupport[HardwareType].SupportList.IsSupported, Mode=TwoWay}"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

AllEffects is ObservableCollection of EffectViewModel where it has a static property called AllSupport which is of type: Dictionary<HardwareType, List<EffectSupport>> where:

HardwareType is an enum, and EffectSupport is an instance class that has a boolean property called IsSupported.

I also tried this but then it complains that it can't find IsSupported on the ViewModel class:

IsChecked="{Binding AllSupport[HardwareType].SupportList, Path=IsSupported

Any ideas, how to specify this binding?

Upvotes: 2

Views: 2079

Answers (2)

v0k
v0k

Reputation: 1

This was my scenario:

  • Had a non-static class with a static property which was a ObservableCollection
  • The class was used as a logger, and to collect specific exceptions from the program

Problem statement:

  • How can I bind a non-static class's static member to a List View in XAML

My Solution:

Code behind(Window.cs):

public ObservableCollection<T> FooList {get {return    FooLogger.ExceptionList;}}
 //where FooLogger is a non-static class
 //and   ExceptionList is a static ObservableCollection<T>

DataContext(Window.cs):

this.DataContext=this;

XAML(Window.xaml)

<ListView ItemsSource="{Binding FooList}">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Width="Auto" Header="Name" DisplayMemberBinding="{Binding Name}" />

Cheers, v0k

Upvotes: 0

Rick Sladkey
Rick Sladkey

Reputation: 34250

You can use x:Static whether the class is static or not to access static members.

Untested:

IsChecked="{Binding [HardwareType], Source={x:Static prefix:EffectViewModel.AllSupport}}"

and you'll need a prefix to access your view model's namespace.

Upvotes: 2

Related Questions