using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using VIZ.Framework.Core;

namespace VIZ.Package.Common
{
    /// <summary>
    /// 右键菜单扩展
    /// </summary>
    public class ContextMenuEx : ContextMenu
    {
        #region BindingTargetType -- 绑定目标类型

        /// <summary>
        /// 绑定目标类型
        /// </summary>
        public Type BindingTargetType
        {
            get { return (Type)GetValue(BindingTargetTypeProperty); }
            set { SetValue(BindingTargetTypeProperty, value); }
        }

        /// <summary>
        /// Using a DependencyProperty as the backing store for BindingTargetType.  This enables animation, styling, binding, etc...
        /// </summary>
        public static readonly DependencyProperty BindingTargetTypeProperty =
            DependencyProperty.Register("BindingTargetType", typeof(Type), typeof(ContextMenuEx), new PropertyMetadata(null));

        #endregion

        /// <summary>
        /// 是否已经完成绑定
        /// </summary>
        private bool IsBinding;

        protected override void OnOpened(RoutedEventArgs e)
        {
            base.OnOpened(e);

            if (this.IsBinding)
                return;

            this.IsBinding = true;

            if (this.BindingTargetType == null)
                return;

            FrameworkElement src = this.PlacementTarget as FrameworkElement;
            if (src == null)
                return;

            FrameworkElement target = WPFHelper.GetAncestorByType(src, this.BindingTargetType) as FrameworkElement;
            if (target == null)
                return;

            this.DataContext = target.DataContext;
        }
    }
}
