Observablecollection does not Binding

Asked

Viewed 155 times

3

I have the following situation:

I make the instance of a property observable in the constructor:

    public ObservableCollection<Model.OSModel> _os { get; private set; }

    public EditorServicosViewModel()
    {
        OS = new ObservableCollection<Model.OSModel>();
    }

When adding an item to the collection within a method:

    public void OnTabClicked(ListaServicosTab listaServicosTab)
    {
        OS.Add(listaServicosTab.vm.OSItem);
        OnPropertyChanged("OS");
    }

He doesn’t connect with the TextBlock. But if I do the instance inside the método:

    public void OnTabClicked(ListaServicosTab listaServicosTab)
    {
        OS = new ObservableCollection<Model.OSModel>();
        OS.Add(listaServicosTab.vm.OS);
        OnPropertyChanged("OS");
    }

He does the Binding.

Someone can tell me the reason for this, because I have done numerous juggling and I can not solve, because I do not want the instance within the method but in the constructor.

  • 1

    Review the property statement There’s something wrong with this public ObservableCollection<Model.OSModel> _os; { get; private set; }

  • Won’t be public ObservableCollection<Model.OSModel> OS { get; private set; }?

2 answers

3

Probably the problem is the encapsulation of the _os property:

public ObservableCollection<Model.OSModel> _os { get; private set; }

As the method set is private, the Binding that is performed by the System.Data library does not have access to it, try to remove the encapsulation from the set method, as below:

public ObservableCollection<Model.OSModel> _os { get; set; }

0

The Observablecollection is a class that makes "Binding" with the itemSource property. So only the elements that have that property do the "Listens" of the collection.

You are Binding with a textblock that does not contain the itemSource property but if you want to continue with the textblock you have to use create a convert class that implements the interface IValueConverter. But I recommend you use one ItemsControl inside the textblock and defining the ItemTemplate with a textblock.

.Cs:

public ObservableCollection<Model.OSModel> OS { get; private set; }

public EditorServicosViewModel()
{
    OS = new ObservableCollection<Model.OSModel>();
    itemscontrol.ItemsSource = OS;
}

XAML:

 <TextBlock x:Name="textBlock" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" Width="654">
                     <ItemsControl x:Name="itemscontrol">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding }"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</TextBlock>

Or use a list control with the listview or listbox

Browser other questions tagged

You are not signed in. Login or sign up in order to post.