using System.Linq;
using System.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;

namespace DisableCellBasedOnValueInAnotherCell
{
    public class DisableCellBehavior
    {
        private RadGridView radGridView;

        public int Value { get; set; }

        public void Attach(RadGridView gridView)
        {
            this.radGridView = gridView;
            this.radGridView.CellEditEnded += this.OnCellEditEnded;
        }

        public void Detach()
        {
            this.radGridView.CellEditEnded -= this.OnCellEditEnded;
            this.radGridView = null;
        }

        private void OnCellEditEnded(object sender, GridViewCellEditEndedEventArgs e)
        {
            if (e.NewData is int)
            {
                var intColumn = (int) e.NewData;

                GridViewCell firstCellOnRow = this.radGridView.ChildrenOfType<GridViewCell>().Where(c => c.ParentRow == e.Cell.ParentRow).First();

                firstCellOnRow.IsEnabled = intColumn <= this.Value;
            }
        }
    }

    public static class AttachedBehavior
    {
        public static readonly DependencyProperty DisableCellBehaviorProperty =
            DependencyProperty.RegisterAttached(
                "DisableCellBehavior", typeof(DisableCellBehavior), typeof(AttachedBehavior), new PropertyMetadata(null, OnDisableCellBehaviorChanged));

        public static DisableCellBehavior GetDisableCellBehavior(DependencyObject obj)
        {
            return (DisableCellBehavior) obj.GetValue(DisableCellBehaviorProperty);
        }

        public static void SetDisableCellBehavior(DependencyObject obj, DisableCellBehavior value)
        {
            obj.SetValue(DisableCellBehaviorProperty, value);
        }

        private static void OnDisableCellBehaviorChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue != null)
            {
                ((DisableCellBehavior) e.OldValue).Detach();
            }

            var gridView = obj as RadGridView;
            if (gridView != null && e.NewValue != null)
            {
                ((DisableCellBehavior) e.NewValue).Attach(gridView);
            }
        }
    }
}