Пример #1
0
        /// <summary>
        /// Creates a new instance of <see cref="Column"/> class.
        /// </summary>
        public GridButtonCommand()
        {
            RelativeSource src = new RelativeSource(RelativeSourceMode.FindAncestor);

            src.AncestorType    = typeof(DataGrid);
            this.RelativeSource = src;
        }
Пример #2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Binding"/> class with initial
        /// property values copied from the specified <see cref="Binding"/>.
        /// </summary>
        /// <param name="original">
        /// The <see cref="Binding"/> to copy.
        /// </param>
        public Binding(Binding original)
        {
            if (original != null)
            {
                FallbackValue   = original.FallbackValue;
                TargetNullValue = original.TargetNullValue;
                StringFormat    = original.StringFormat;

                _isInStyle = original._isInStyle;
                _converter = original._converter;
#if MIGRATION
                _culture = original._culture;
#else
                _culture = original._culture;
#endif
                _converterParameter = original._converterParameter;
                _elementName        = original._elementName;
                _mode                        = original._mode;
                _xamlPath                    = original._xamlPath;
                _path                        = original._path;
                _relativeSource              = original._relativeSource;
                _source                      = original._source;
                _updateSourceTrigger         = original._updateSourceTrigger;
                _validatesOnExceptions       = original._validatesOnExceptions;
                _notifyOnValidationError     = original._notifyOnValidationError;
                _bindsDirectlyToSource       = original._bindsDirectlyToSource;
                _validatesOnNotifyDataErrors = original._validatesOnNotifyDataErrors;
                _validatesOnDataErrors       = original._validatesOnDataErrors;

                _wasModeSetByUserRatherThanDefaultValue = original._wasModeSetByUserRatherThanDefaultValue;
            }
        }
        /// <summary>
        /// Gets a binding source as a <see cref="RelativeSource"/> of a <see cref="DependencyObject"/>.
        /// </summary>
        /// <param name="relativeSource"><see cref="RelativeSource"/> value for seeking.</param>
        /// <param name="root">Root reference object.</param>
        /// <returns>The source object that is relatated to the reference one, if any found, null otherwise.</returns>
        internal static object GetSourceFromRelativeSource(RelativeSource relativeSource, DependencyObject root)
        {
            if (relativeSource == null)
            {
                return(root);
            }

            if (relativeSource.Mode == RelativeSourceMode.FindAncestor)
            {
                if (relativeSource.AncestorType != null)
                {
                    return(root.FindParentByType(relativeSource.AncestorType));
                }
                else if (relativeSource.AncestorLevel > 0)
                {
                    return(WPFVisualFinders.FindParentByLevel(root, relativeSource.AncestorLevel));
                }
            }
            else if (relativeSource.Mode == RelativeSourceMode.Self)
            {
                return(root);
            }
            else if (relativeSource.Mode == RelativeSourceMode.PreviousData)
            {
                //TODO.
                throw new NotSupportedException(nameof(RelativeSourceMode.PreviousData) + " is currently not supported.");
            }
            else if (relativeSource.Mode == RelativeSourceMode.TemplatedParent)
            {
                //TODO.
                throw new NotSupportedException(nameof(RelativeSourceMode.TemplatedParent) + " is currently not supported.");
            }
            return(root);
        }
Пример #4
0
        public MainWindow()
        {
            InitializeComponent();

            //不确定数据源的名字叫什么, 但可以通过xaml的结构查找到, 比如: 查询上一层的gird类型的元素的Name,
            //这时可以是使用RelativeSource绑定。

            //从txtBox的的第一层开始,从内向外查找第一个grid,并且把grid的name属性绑定给textBox的Text

            //1. 查找第一层的grid对象
            //RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
            //rs.AncestorLevel = 1;
            //rs.AncestorType = typeof(Grid);

            //2. 查找第二层的DockPanel对象
            //RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);
            //rs.AncestorLevel = 2;
            //rs.AncestorType = typeof(DockPanel);

            //3. 查找自己的name
            RelativeSource rs = new RelativeSource();

            rs.Mode = RelativeSourceMode.Self;

            Binding binding = new Binding("Name")
            {
                RelativeSource = rs
            };

            this.txtBox.SetBinding(TextBox.TextProperty, binding);
        }
Пример #5
0
        private static object FindRelativeSource(BindingExpression expr)
        {
            RelativeSource relativeSource = expr.ParentBinding.RelativeSource;

            switch (relativeSource.Mode)
            {
            case RelativeSourceMode.Self:
                return(expr.Target);

            case RelativeSourceMode.TemplatedParent:
                if (expr.ParentBinding.TemplateOwner != null)
                {
                    return(expr.ParentBinding.TemplateOwner.TemplateOwner);
                }

                // todo: find out why we enter here in Client_TUI.
                Debug.WriteLine("ERROR: ParentBinding.TemplateOwner is null.");
                return(null);

            case RelativeSourceMode.FindAncestor:
                return(FindAncestor(expr.Target, relativeSource));

            case RelativeSourceMode.None:
            default:
                return(null);
            }
        }
Пример #6
0
 private void ApplyParentContext()
 {
     // Set the path relative to the DataContext
     Path = new PropertyPath(string.Join(Separators.Point, "DataContext", Path?.Path ?? string.Empty));
     // Set the parent ItemsControl as relative source
     RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ItemsControl), 1);
 }
 private void Initialize()
 {
     RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(MainWindow), 1);
     Path           = new System.Windows.PropertyPath("Busy");
     Converter      = new BoolNotConverter();
     Mode           = BindingMode.OneWay;
 }
Пример #8
0
        public static DependencyObject Resolve(this RelativeSource subject, DependencyObject source)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            switch (subject.Mode)
            {
            case RelativeSourceMode.FindAncestor:
                return(new UpwardTreeWalk <DependencyObject>(source, LogicalTreeHelper.GetParent).Skip(subject.AncestorLevel - 1).First());

            case RelativeSourceMode.PreviousData:
                throw new NotImplementedException("Mode = RelativeSourceMode.PreviousData not implemented.");

            default:
            case RelativeSourceMode.Self:
                return(source);

            case RelativeSourceMode.TemplatedParent:
                throw new NotImplementedException("Mode = RelativeSourceMode.TemplatedParent not implemented.");
            }
        }
Пример #9
0
        private void InitialLayoutControl()
        {
            for (int i = 0; i < 15; i++)
            {
                Button btn = new Button();
                btn.Width  = 40;
                btn.Height = 40;
                btn.Margin = new Thickness(10);
                btn.Tag    = i;
                btn.Style  = Application.Current.FindResource("btnPicLayoutStyle") as Style;
                Binding bdcmd = new Binding("LayoutButtonCommand");
                btn.SetBinding(Button.CommandProperty, bdcmd);
                RelativeSource rs = new RelativeSource();
                rs.Mode = RelativeSourceMode.Self;
                Binding bdcmdparam = new Binding("Tag")
                {
                    RelativeSource = rs
                };
                btn.SetBinding(Button.CommandParameterProperty, bdcmdparam);

                Image       img = new Image();
                BitmapImage bi  = new BitmapImage();
                bi.BeginInit();
                bi.UriSource = new Uri(string.Format("PicLayoutIcon/{0}.png", i), UriKind.Relative);
                bi.EndInit();
                img.Source  = bi;
                btn.Content = img;

                wrapLayout.Children.Add(btn);
            }

            this.ShowLayoutMergeTool();
        }
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DependencyPropertyWatcher{T}"/> class.
 /// </summary>
 /// <param name="relativesource">Databind relative source info</param>
 /// <param name="propertyPath">Property path.</param>
 public DependencyPropertyWatcher(RelativeSource relativesource, PropertyPath propertyPath)
 {
     Source = relativesource;
     BindingOperations.SetBinding(this, ValueProperty, new Binding()
     {
         RelativeSource = relativesource, Path = propertyPath, Mode = BindingMode.OneWay
     });
 }
 // Token: 0x060075FE RID: 30206 RVA: 0x0021A63F File Offset: 0x0021883F
 internal RelativeObjectRef(RelativeSource relativeSource)
 {
     if (relativeSource == null)
     {
         throw new ArgumentNullException("relativeSource");
     }
     this._relativeSource = relativeSource;
 }
Пример #12
0
        public GridViewColumn GetColumn(string header, SolidColorBrush background, string binding, string width, string foregroundBinding, TextAlignment textAlignment)
        {
            GridViewColumn gvc = new GridViewColumn();

            gvc.Header = header;

            var tb = new FrameworkElementFactory(typeof(TextBlock));

            tb.SetValue(TextBlock.MarginProperty, new Thickness(-6, 0, -6, 0));
            tb.SetValue(TextBlock.PaddingProperty, new Thickness(5, 0, 5, 0));
            tb.SetValue(TextBlock.VerticalAlignmentProperty, VerticalAlignment.Center);
            tb.SetValue(TextBlock.BackgroundProperty, background);
            tb.SetValue(TextBlock.ForegroundProperty, Brushes.White);
            tb.SetValue(TextBlock.ForegroundProperty, Brushes.White);
            tb.SetValue(TextBlock.TextAlignmentProperty, textAlignment);

            if (width != "")
            {
                gvc.SetValue(WidthProperty, Double.Parse(width));
            }

            Binding bText = new Binding();

            bText.Path = new PropertyPath(binding);

            if (foregroundBinding != "")
            {
                Binding bForeground = new Binding();
                bForeground.Path = new PropertyPath(foregroundBinding);
                tb.SetBinding(TextBlock.ForegroundProperty, bForeground);
            }


            Binding bHeight = new Binding();

            bHeight.Path = new PropertyPath("ActualHeight");
            RelativeSource rsH = new RelativeSource();

            rsH.Mode               = RelativeSourceMode.FindAncestor;
            rsH.AncestorType       = typeof(ListViewItem);
            rsH.AncestorLevel      = 1;
            bHeight.RelativeSource = rsH;

            tb.SetBinding(TextBlock.TextProperty, bText);
            tb.SetBinding(TextBlock.HeightProperty, bHeight);


            DataTemplate dt = new DataTemplate()
            {
                VisualTree = tb
            };

            gvc.CellTemplate = dt;


            return(gvc);
        }
Пример #13
0
 public AncestorReference(string path, Type type) : base(path)
 {
     Converter      = new SimpleConverter <object, Reference>(i => new Reference(i), null);
     Mode           = BindingMode.OneWay;
     RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor)
     {
         AncestorType = type
     };
 }
Пример #14
0
 public IsDesignBind()
 {
     RelativeSource = new RelativeSource()
     {
         Mode = RelativeSourceMode.Self
     };
     //Path = DesignerProperties.IsInDesignModeProperty;
     Path = new System.Windows.PropertyPath(DesignerProperties.IsInDesignModeProperty);
 }
Пример #15
0
        void MoveThumb_Loaded(object sender, RoutedEventArgs e)
        {
            Binding        binding = new Binding();
            RelativeSource rs      = new RelativeSource(RelativeSourceMode.TemplatedParent);

            binding.RelativeSource = rs;
            binding.Path           = new PropertyPath(".");
            this.SetBinding(Thumb.DataContextProperty, binding);
        }
Пример #16
0
        /// <summary>
        /// Returns a clone of this binding but with a different value for the 'RelativeSource' property.
        /// Using this method is required if you wish to set a RelativeSource and the original binding uses
        /// ElementName or Source.
        /// </summary>
        /// <param name="subject">The binding.</param>
        /// <param name="newRelativeSource">The new value for RelativeSource.</param>
        /// <returns>The clone.</returns>
        public static Binding Clone(this Binding subject, RelativeSource newRelativeSource)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }

            return(BindingExtensions.Clone(subject, null, newRelativeSource, null));
        }
Пример #17
0
        public override object ProvideValue(IServiceProvider provider)
        {
            if (RelativeSource == null)
            {
                RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, AncestorType, AncestorLevel);
            }

            return(base.ProvideValue(provider));
        }
        /// <summary>
        /// Ctor.
        /// Initializes <see cref="_pp"/>  and <see cref="_rs"/>.
        /// If the <see cref="PropertyPath.Path"/> is "." or <see cref="String.Empty"/> then a <see cref="RelativeSource"/> binding is configured.
        /// </summary>
        /// <param name="path">Path to the property.</param>
        public BindingEvaluator(string path)
        {
            var isrel = path == "." || String.IsNullOrEmpty(path);

            _pp = isrel ? null : new PropertyPath(path);
            _rs = isrel ? new RelativeSource()
            {
                Mode = RelativeSourceMode.Self
            } : null;
        }
Пример #19
0
        private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
        {
            var IsSelected  = ((ExcelDialogViewModel)DataContext).IsSelected;
            var ColumnColor = ((ExcelDialogViewModel)DataContext).ColumnColor;

            IsSelected.Clear();
            ColumnColor.Clear();

            RelativeSource RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor)
            {
                AncestorType = GetType()
            };
            var context = (ExcelDialogViewModel)DataContext;

            for (int i = 0; i < DataGrid.Columns.Count; i++)
            {
                IsSelected.Add(false);
                if (i == context.DateColumnIndex)
                {
                    context.Mode  = 1;
                    context.Label = "Please select your schedule column";
                    ColumnColor.Add(context.DateColumnColor);
                }
                else
                {
                    ColumnColor.Add(Brushes.White);
                }

                DataGrid.Columns[i].CellStyle = new Style
                {
                    TargetType = typeof(DataGridCell),
                    Setters    =
                    {
                        new Setter
                        {
                            Property = DataGridCell.IsSelectedProperty,
                            Value    = new Binding(string.Format("DataContext.IsSelected[{0}]", i))
                            {
                                RelativeSource = RelativeSource, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                            },
                        },
                        new Setter
                        {
                            Property = DataGridCell.BackgroundProperty,
                            Value    = new Binding(string.Format("DataContext.ColumnColor[{0}]", i))
                            {
                                RelativeSource = RelativeSource, Mode = BindingMode.Default, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
                            },
                        }
                    },
                };
            }
        }
Пример #20
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="SwitchBindingExtension" /> class.
 /// </summary>
 /// <param name="relativeSource">The relative source.</param>
 /// <param name="path">The binding path.</param>
 /// <param name="valueIfTrue">The value if true.</param>
 /// <param name="valueIfFalse">The value if false.</param>
 public SwitchBindingExtension(
     RelativeSource relativeSource,
     string path,
     object valueIfTrue,
     object valueIfFalse)
     : base(path)
 {
     this.Initialize();
     this.RelativeSource = relativeSource;
     this.ValueIfTrue    = valueIfTrue;
     this.ValueIfFalse   = valueIfFalse;
 }
Пример #21
0
        private void RelativeSource()
        {
            RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);

            rs.AncestorLevel = 1;
            rs.AncestorType  = typeof(Grid);
            Binding binding = new Binding("Name")
            {
                RelativeSource = rs
            };

            this.textBox2.SetBinding(TextBox.TextProperty, binding);
        }
Пример #22
0
        public Window15()
        {
            InitializeComponent();

            RelativeSource rs = new RelativeSource(RelativeSourceMode.Self);

            Binding bind = new Binding("Name")
            {
                RelativeSource = rs
            };

            this.textBox1.SetBinding(TextBox.TextProperty, bind);
        }
Пример #23
0
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Button         btn = sender as Button;
            RelativeSource rs  = new RelativeSource(RelativeSourceMode.FindAncestor);

            rs.AncestorType = typeof(ListBoxItem);
            Binding binding = new Binding("Tag")
            {
                RelativeSource = rs
            };

            btn.SetBinding(Button.ContentProperty, binding);
        }
Пример #24
0
        private static void RegisterDependencyPropertyBinding(
            FrameworkElement element, string dependencyPropertyToBind, DependencyProperty attachedDp)
        {
            var bindingSource = new RelativeSource {
                Mode = RelativeSourceMode.Self
            };
            var dependencyPropertyExtensionBinding = new Binding
            {
                Path           = new PropertyPath(dependencyPropertyToBind),
                RelativeSource = bindingSource
            };

            element.SetBinding(attachedDp, dependencyPropertyExtensionBinding);
        }
Пример #25
0
        static GroupByControl()
        {
            // This DefaultStyleKey will only be used in design-time.
            DefaultStyleKeyProperty.OverrideMetadata(typeof(GroupByControl), new FrameworkPropertyMetadata(new Markup.ThemeKey(typeof(Views.TableView), typeof(GroupByControl))));

            FrameworkElementFactory staircaseFactory   = new FrameworkElementFactory(typeof(StaircasePanel));
            ItemsPanelTemplate      itemsPanelTemplate = new ItemsPanelTemplate(staircaseFactory);
            RelativeSource          ancestorSource     = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(GroupByControl), 1);

            Binding binding = new Binding();

            binding.Path           = new PropertyPath(GroupByControl.ConnectionLineAlignmentProperty);
            binding.Mode           = BindingMode.OneWay;
            binding.RelativeSource = ancestorSource;
            staircaseFactory.SetBinding(StaircasePanel.ConnectionLineAlignmentProperty, binding);

            binding                = new Binding();
            binding.Path           = new PropertyPath(GroupByControl.ConnectionLineOffsetProperty);
            binding.Mode           = BindingMode.OneWay;
            binding.RelativeSource = ancestorSource;
            staircaseFactory.SetBinding(StaircasePanel.ConnectionLineOffsetProperty, binding);

            binding                = new Binding();
            binding.Path           = new PropertyPath(GroupByControl.ConnectionLinePenProperty);
            binding.Mode           = BindingMode.OneWay;
            binding.RelativeSource = ancestorSource;
            staircaseFactory.SetBinding(StaircasePanel.ConnectionLinePenProperty, binding);

            binding                = new Binding();
            binding.Path           = new PropertyPath(GroupByControl.StairHeightProperty);
            binding.Mode           = BindingMode.OneWay;
            binding.RelativeSource = ancestorSource;
            staircaseFactory.SetBinding(StaircasePanel.StairHeightProperty, binding);

            binding                = new Binding();
            binding.Path           = new PropertyPath(GroupByControl.StairSpacingProperty);
            binding.Mode           = BindingMode.OneWay;
            binding.RelativeSource = ancestorSource;
            staircaseFactory.SetBinding(StaircasePanel.StairSpacingProperty, binding);

            itemsPanelTemplate.Seal();

            ItemsControl.ItemsPanelProperty.OverrideMetadata(typeof(GroupByControl), new FrameworkPropertyMetadata(itemsPanelTemplate));

            DataGridControl.ParentDataGridControlPropertyKey.OverrideMetadata(typeof(GroupByControl), new FrameworkPropertyMetadata(new PropertyChangedCallback(GroupByControl.ParentGridControlChangedCallback)));
            DataGridControl.DataGridContextPropertyKey.OverrideMetadata(typeof(GroupByControl), new FrameworkPropertyMetadata(new PropertyChangedCallback(GroupByControl.DataGridContextChangedCallback)));

            FocusableProperty.OverrideMetadata(typeof(GroupByControl), new FrameworkPropertyMetadata(false));
        }
Пример #26
0
        public static void SetBinding(
            string pathString,
            DependencyObject target,
            DependencyProperty targetProperty)
        {
            Binding        binding        = new Binding();
            RelativeSource relativeSource = new RelativeSource();

            relativeSource.Mode    = RelativeSourceMode.TemplatedParent;
            binding.RelativeSource = relativeSource;

            binding.Path = new PropertyPath(pathString);

            BindingOperations.SetBinding(target, targetProperty, binding);
        }
Пример #27
0
        internal void SetValueTextDefaultStyle()
        {
            this.ValueText.Style = Defaults.DefaultValueTextStyle;
            // Set up the default margin binding
            Binding b = new Binding("Height");

            b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            var relSource = new RelativeSource();

            relSource.Mode         = RelativeSourceMode.FindAncestor;
            relSource.AncestorType = typeof(Gauge);
            b.RelativeSource       = relSource;
            b.Converter            = new WpfGauge.Converters.ValueTextMarginConverter();
            this.ValueText.SetBinding(TextBlock.MarginProperty, b);
        }
Пример #28
0
        public UserControl3()
        {
            InitializeComponent();

            var source = new RelativeSource(RelativeSourceMode.FindAncestor);

            source.AncestorType = this.GetType();
            var b = new Binding();

            //b.Source = this;
            b.RelativeSource = source;
            b.Mode           = BindingMode.TwoWay;
            b.Path           = new PropertyPath(nameof(Value));
            textBlockValue.SetBinding(TextBlock.TextProperty, b);
        }
Пример #29
0
        public AncestorBinding(string path) : base(path)
        {
            if (!IsPropertyReference(path))
            {
                throw new ArgumentException("Ancestor type not specified in path '{0}'.".Fmt(path), "path");
            }
            string propRef       = path.Substring(1, path.IndexOf(')') - 1);
            string ownerTypeName = propRef.Substring(0, propRef.LastIndexOf('.')).Trim();
            Type   ownerType     = GetTypeFromName(Path, ownerTypeName);

            if (ownerType == null)
            {
                throw new ArgumentException("Ancestor type '{0}' not found using path '{1}'.".Fmt(ownerTypeName, path), "path");
            }
            RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, ownerType, 1);
        }
Пример #30
0
        public Window15()
        {
            InitializeComponent();

            RelativeSource rs = new RelativeSource(RelativeSourceMode.FindAncestor);

            rs.AncestorLevel = 2;
            rs.AncestorType  = typeof(Grid);

            Binding bind = new Binding("Name")
            {
                RelativeSource = rs
            };

            this.textBox1.SetBinding(TextBox.TextProperty, bind);
        }