Quantcast
Channel: Xamarin.Forms — Xamarin Community Forums
Viewing all articles
Browse latest Browse all 89864

Why doesnt an ObservableCollection bound to a label via a convertor fire on Collectionchange?

$
0
0

I have a label with the text bound to an ObservableCollection via a converter. When the page loads the converter fires and sets the text. I would expect that any changes to the collection would fire a CollectionChanged Event and cause the converter to update the label this however doesn't seem to be happening. Even an explicit call to "OnPropertyChanged" seems to have no effect can anyone see why?

App.cs

    public class App : Application
    {
        public ObservableCollection<string> MyColl { get; set; }

        private void MyCollChanged(object sender, EventArgs e)
        {
            OnPropertyChanged("MyColl");
        }


        public App ()
        {
            MyColl = new ObservableCollection<string>();

            //Just cause so noone says to do it;
            MyColl.CollectionChanged+=MyCollChanged;

            Label counter =new Label(){FontSize=30};

            Button incer =new Button(){Text="Inc It"};
            incer.Clicked += (sender, e) => MyColl.Add (DateTime.Now.ToString());

            ListView viewIt = new ListView ();
            viewIt.ItemsSource = MyColl;

            var counterTextBinding = new Binding();
            counterTextBinding.Mode = BindingMode.TwoWay; 
            counterTextBinding.Converter=new CollectionConvertor();
            counterTextBinding.Source = MyColl;
            counter.SetBinding(Label.TextProperty,counterTextBinding);


            // The root page of the application
            MainPage = new ContentPage {
                Content = new StackLayout {
                    VerticalOptions = LayoutOptions.Center,
                    Children = {counter,incer,viewIt
                    }
                }
            };
        }
    }

CollectionConvertor.cs

    public class CollectionConvertor: IValueConverter
    {
        public CollectionConvertor(){}

        public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return ((ObservableCollection<string>)value).Count.ToString();
        }
        public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException ();
        }
    }

Viewing all articles
Browse latest Browse all 89864

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>