Problems binding static ObservableCollection

I have a class (very small code for testing) that contains a static ObservableCollectionone that populates from another place:

public class TestClass
{
    public static ObservableCollection<int> TestCollection = new ObservableCollection<int>();
}

... and the WPF base window with ListBox:

<Window x:Class="app.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="list"/>
    </Grid>
</Window>

When I tried to link programmatically:

list.ItemsSource = Containers.TestClass.TestCollection;

... it worked fine. However, when I try to bind through XAML:

<Window x:Class="app.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="clr-namespace:app.Containers"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <d:TestClass x:Key="dataSource"/>
    </Window.Resources>
    <Grid>
        <ListBox x:Name="list" ItemsSource="{Binding Source={StaticResource dataSource}, Path=TestCollection}"/>
    </Grid>
</Window>

... nothing is displayed.

I also tried to install DataContext:

<Window.Resources>
    <l:LifeEngine x:Key="dataSource"/>
</Window.Resources>
<Window.DataContext>
    <Binding Source="{StaticResource dataSource}"/>
</Window.DataContext>

... and using the path ...

... and nothing is displayed again.

Also, not sure if that matters, but when I make my class static, I get an error in the XAML code:

The TestClass type is abstract and must contain an explicit value.

So, that is out of the question.

, ObservableCollection XAML?

+4
1

, .

<ListBox ItemsSource="{Binding Source={StaticResource dataSource},
                               Path=TestCollection}"/>

dataSource TestClass Path to TestCollection, TestCollection, . .

x:Static. ( , TestClass)

<ListBox ItemsSource="{Binding Source={x:Static d:TestClass.TestCollection}}"/>

, . , . ObservableCollection, , / , , , . , StaticPropertyChangedEvent. .

+9

Source: https://habr.com/ru/post/1531992/


All Articles