ObservableCollection does not bind

3

I have the following situation:

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

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

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

When I add an item to the collection within a method:

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

It does not bind to TextBlock . But if I make the instance inside método :

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

It does the binding.

Someone can tell me the reason for this, because I have already done a lot of juggling and I can not solve it, because I do not want the instance inside the method but in the constructor.

    
asked by anonymous 16.02.2016 / 19:21

2 answers

3

Probably the problem is the encapsulation of the _os property:

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

Since the set method is private, the binding that is performed by the System.Data library does not have access to it, try removing the encapsulation from the set method, as follows:

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

    
25.05.2016 / 20:01
0

The ObservableCollection is a class that binds with the itemSource property. Then only the elements that have such a property make the listens of the collection.

You are binding with a textblock that does not contain the itemSource property however if you want to continue with the textblock you have to use create a convert class that implements the IValueConverter interface. But I recommend that you use ItemsControl within the textblock and setting ItemTemplate to 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 listview or listbox

    
26.05.2016 / 13:50