using System.Linq;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using Silverlight_LearningToUseBehaviors.Behaviors;

namespace Silverlight_LearningToUseBehaviors
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            
            // keeping it simple for the demo
            DataContext = new MainPageViewModel();

            AttachImmediateBehavior();
        }

        private void AttachImmediateBehavior()
        {
            //SearchTextBox
            var behaviorCollection = Interaction.GetBehaviors(SearchTextBox);

            if ( behaviorCollection.Count(x => x.GetType() == typeof(ImmediateUpdateBehavior)) == 0)
            {
                behaviorCollection.Add(new ImmediateUpdateBehavior());
            }
        }

        private void DetachImmediateBehavior()
        {
            //SearchTextBox
            var behaviorCollection = Interaction.GetBehaviors(SearchTextBox);
            var foundBehaviors = behaviorCollection.Where(x => x.GetType() == typeof (ImmediateUpdateBehavior)).ToList();

            if( foundBehaviors.Count > 0)
            {
                foundBehaviors.ForEach(x => behaviorCollection.Remove(x));
            }
        }

        private void button1_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            DetachImmediateBehavior();
        }
    }
}