C#C
C#3y ago
ivi

✅ WPF thinks my collection has no items

It's a bit much to explain with full context, but the gist is:

An Action has a Fields which has a list of Field.

public partial class ActionViewModel : ViewModelBase
{
    [ObservableProperty] private FieldsViewModel _fields1;

    public ActionViewModel(FxrModel.Action action)
    {
        _fields1 = new FieldsViewModel(action.Fields1);


public partial class FieldsViewModel : ViewModelBase
{
    [ObservableProperty] private ObservableCollection<FieldViewModel> _fields;

    public FieldsViewModel(List<FxrModel.Field> fields)
    {
        _fields = new ObservableCollection<FieldViewModel>();


public partial class FieldViewModel : ViewModelBase
{
    [ObservableProperty] private FxrModel.Field _field;

    public Fxr3.FieldType Type => _field.Type;

    public object Value
    {
        get => _field.Value;
        set
        {
            OnPropertyChanging();
            _field.Value = value;
            OnPropertyChanged();
        }
    }

    public FieldViewModel(FxrModel.Field field)
    {
        _field = field;
    }
}


Each of the viewmodels is bound to a View.

ActionView has:

        <Label Content="{Binding Fields1.Fields.Count}" ContentStringFormat="Fields1: {0}" />
        <local:RawFieldsView DataContext="{Binding Fields1}" />


RawFieldsView has:
    <StackPanel>
        <Label Content="{Binding Fields.Count}" />
        <ItemsControl ItemsSource="{Binding Fields}">
        <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <Label HorizontalAlignment="Right" Margin="{adonisUi:Space 0, 1.3, 1, 0}"
                               Content="{Binding Type}" />
                        <TextBox Margin="{adonisUi:Space 0, 1, 0, 0}" Text="{Binding Value }" />
                    </WrapPanel>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>


But no matter what, Fields.Count always displays 0, and the ItemsControl is empty.

I have confirmed that the underlying ViewModels definitely have filled collections with stuff in them. There are definitely not 0 Fields in the Action.

And yet, that's what WPF says!

Any clues?
2023-08-16_03-39-25__RainbowStoneMVVM.png
Was this page helpful?