Exemple #1
0
        /// <summary>
        ///     Returns a <see cref="BindingProxy" /> bound to the value returned by <see cref="ProvideValue" />.
        /// </summary>
        /// <param name="name">Resource name. This is not the object property name.</param>
        /// <returns></returns>
        public BindingProxy this[string name]
        {
            get
            {
                if (proxyCache.TryGetValue(name, out var proxy))
                {
                    return(proxy);
                }

                proxy            = new BindingProxy();
                proxyCache[name] = proxy;
                var value = ProvideValue(name);
                if (value is BindingBase binding)
                {
                    BindingOperations.SetBinding(proxy, BindingProxy.ValueProperty, binding);
                }
                else
                {
                    proxy.Value = value;
                }

                return(proxy);
            }
        }
Exemple #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="edge"></param>
        protected void AddEdge(NodeEdge edge)
        {
            // Skip if it it already been added
            if (graph.ContainsEdge(edge))
            {
                return;
            }

            // Add the vertex to the logic graph
            graph.AddEdge(edge);

            // Create the vertex control
            var control = AssociatedObject.ControlFactory.CreateEdgeControl(AssociatedObject.VertexList[edge.Source], AssociatedObject.VertexList[edge.Target], edge);

            control.DataContext = edge;
            //control.Visibility = Visibility.Hidden; // make them invisible (there is no layout positions yet calculated)

            // Create data binding for input slots and output slots
            var binding = new Binding();

            binding.Path   = new PropertyPath("SourceSlot");
            binding.Mode   = BindingMode.TwoWay;
            binding.Source = edge;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(control, NodeEdgeControl.SourceSlotProperty, binding);

            binding        = new Binding();
            binding.Path   = new PropertyPath("TargetSlot");
            binding.Mode   = BindingMode.TwoWay;
            binding.Source = edge;
            binding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
            BindingOperations.SetBinding(control, NodeEdgeControl.TargetSlotProperty, binding);

            // Add vertex and control to the graph area
            AssociatedObject.AddEdge(edge, control);
        }
        private void ChangeToDeferredBinding(TextBox element)
        {
            var originalBinding = BindingOperations.GetBinding(element, TextBox.TextProperty) ?? (BindingBase)BindingOperations.GetMultiBinding(element, TextBox.TextProperty);

            SetOriginalBinding(element, originalBinding);
            SetInputDeferrer(element, this);

            var newBinding = CreateNewBinding(element);

            var text = (string)GetDeferredValue(element) ?? element.Text;

            if (text != element.Text && !ChangesAvailable)
            {
                text = element.Text;
            }

            //BindingOperations.ClearBinding(element, DeferredValueProperty);
            BindingOperations.ClearBinding(element, TextBox.TextProperty);

            element.SetValue(TextBox.TextProperty, text);

            //TODO: check if can remove the clear.
            BindingOperations.SetBinding(element, DeferredValueProperty, newBinding);
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            var mainHeader = Template.FindName("MainHeader", this) as MenuItem;

            if (mainHeader != null)
            {
                _mainHeader = mainHeader;
            }

            var surface = this.TryFindParent <DesignSurface>();

            if (surface != null && surface.ZoomControl != null)
            {
                var bnd = new Binding("CurrentZoom")
                {
                    Source = surface.ZoomControl
                };
                bnd.Converter = InvertedZoomConverter.Instance;

                BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleXProperty, bnd);
                BindingOperations.SetBinding(scaleTransform, ScaleTransform.ScaleYProperty, bnd);
            }
        }
        private static void SetStyleBinding([NotNull] DependencyObject column, [NotNull] DependencyProperty property, [NotNull] DataGridColumnStyle style)
        {
            // ElementStyle and EditingElementStyle are not defined at the base class, but are different property for e.g. bound and combo box column
            // => use reflection to get the effective property for the specified column.

            var propertyName = property.Name;
            var columnType   = column.GetType();

            var defaultStyle = columnType.GetProperty("Default" + propertyName, BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)?.GetValue(null, null) as Style;
            var activeStyle  = columnType.GetProperty(propertyName)?.GetValue(column, null) as Style;

            if (activeStyle != defaultStyle)
            {
                return;
            }

            if (columnType.GetField(propertyName + "Property", BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)?.GetValue(null) is DependencyProperty targetProperty)
            {
                BindingOperations.SetBinding(column, targetProperty, new Binding(propertyName)
                {
                    Source = style, FallbackValue = defaultStyle
                });
            }
        }
Exemple #7
0
        public void NewGame()
        {
            IsVisible = false;
            DestroyScene();
            var levelView = new LevelView();

            world                = new World(levelView.World);
            world.Player         = new Player(window);
            window.World.Content = levelView;
            window.Hud.Content   = View.Create(world.Player);
            world.Start();
            OnPropertyChanged("CanContinue");

            if (Debugger.IsAttached)
            {
                BindingOperations.SetBinding(
                    window, Window.TitleProperty, new Binding("Fps")
                {
                    Source             = world,
                    Converter          = ValueConverters.FormatString,
                    ConverterParameter = "{0} FPS"
                });
            }
        }
        private void AddColumns(IEnumerable items)
        {
            var actions = new List <Action>();

            foreach (var c in items)
            {
                var info = c as IDynamicGridColumnInfo;
                if (info == null)
                {
                    throw new Exception(
                              "When using DynamicGrid, each element in Columns must implement IDynamicGridColumnInfo.");
                }
                //var column = new DynamicGridColumn(info) { CellTemplate = DynamicGrid.GetColumnTemplate(_grid) };
                var column = new DynamicGridColumn(_grid, info);
                BindingOperations.SetBinding(column, DataGridTemplateColumn.CellTemplateProperty,
                                             new Binding
                {
                    Path   = new PropertyPath("(0)", DynamicGrid.ColumnTemplateProperty),
                    Source = _grid
                });
                actions.Add(delegate
                {
                    column.Header = info.Header;
                    //if (info.DisplayIndex < _grid.Columns.Count)
                    column.DisplayIndex = info.DisplayIndex;
                    column.Width        = info.Width;
                });
                _grid.Columns.Add(column);
            }
            // Performs the initialization of each column. Some properties (e.g. DisplayIndex) must be
            // set after all columns are added in order to avoid a potential ArgumentOutOfRangeException.
            foreach (var action in actions)
            {
                action();
            }
        }
        public static CheckBox CheckBox(Grid grid, string label, bool isReadOnly, string propertyPath)
        {
            // add new definitions to the details grid
            var rowDef = new RowDefinition()
            {
                Height = GridLength.Auto
            };

            grid.RowDefinitions.Add(rowDef);
            int row = grid.RowDefinitions.IndexOf(rowDef);

            // create checkbox
            var checkBox = new CheckBox()
            {
                IsThreeState = false,
                Content      = label,
                IsEnabled    = !isReadOnly
            };

            // set binding
            BindingOperations.SetBinding(checkBox, System.Windows.Controls.CheckBox.IsCheckedProperty, new Binding(propertyPath)
            {
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Mode = BindingMode.TwoWay,
                NotifyOnTargetUpdated = true,
                NotifyOnSourceUpdated = true
            });

            // add checkbox to the details grid
            Grid.SetColumn(checkBox, 0);
            Grid.SetColumnSpan(checkBox, 2);
            Grid.SetRow(checkBox, row);
            grid.Children.Add(checkBox);

            return(checkBox);
        }
 public override void OnApplyTemplate()
 {
     base.OnApplyTemplate();
     this._BackgroundTranslate = base.GetTemplateChild("PART_BackgroundTranslate") as TranslateTransform;
     this._DraggingThumb       = base.GetTemplateChild("PART_DraggingThumb") as Thumb;
     this._SwitchTrack         = base.GetTemplateChild("PART_SwitchTrack") as Grid;
     this._ThumbIndicator      = base.GetTemplateChild("PART_ThumbIndicator") as Shape;
     this._ThumbTranslate      = base.GetTemplateChild("PART_ThumbTranslate") as TranslateTransform;
     if (this._ThumbIndicator != null && this._BackgroundTranslate != null)
     {
         Binding binding = new Binding("X")
         {
             Source = this._ThumbTranslate
         };
         BindingOperations.SetBinding(this._BackgroundTranslate, TranslateTransform.XProperty, binding);
     }
     if (this._DraggingThumb != null && this._SwitchTrack != null && this._ThumbIndicator != null && this._ThumbTranslate != null)
     {
         this._DraggingThumb.DragStarted   += new DragStartedEventHandler(this._DraggingThumb_DragStarted);
         this._DraggingThumb.DragDelta     += new DragDeltaEventHandler(this._DraggingThumb_DragDelta);
         this._DraggingThumb.DragCompleted += new DragCompletedEventHandler(this._DraggingThumb_DragCompleted);
         this._SwitchTrack.SizeChanged     += new SizeChangedEventHandler(this._SwitchTrack_SizeChanged);
     }
 }
        public override void OnCreateCustomElements(IList <Gripper> grippers, IList <FrameworkElement> foregroundElements)
        {
            ForEachAbsPoint(args =>
            {
                if (args.Object != null && args.Path != null)
                {
                    args.Gripper = Gripper.CreateCircleGripper();

                    var binding    = new Binding(args.Path);
                    binding.Source = args.Object;
                    binding.Mode   = BindingMode.TwoWay;
                    BindingOperations.SetBinding(args.Gripper, Gripper.PositionProperty, binding);

                    grippers.Add(args.Gripper);

                    if (args.ParentPoint != null)
                    {
                        var pr = new PointRalation(args, args.ParentPoint);
                        _PointRalations.Add(pr);
                        foregroundElements.Add(pr.Line);
                    }
                }
            });
        }
        public void WhenRequiredUpdateSourceOnErrorIfUpdateSourceOnError()
        {
            var vm = new DummyViewModel {
                NullableDoubleValue = 1
            };
            var textBox = new TextBox {
                DataContext = vm
            };
            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                Mode = BindingMode.TwoWay
            };

            textBox.SetIsRequired(true);
            textBox.SetOnValidationErrorStrategy(OnValidationErrorStrategy.UpdateSourceOnError);
            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.RaiseLoadedEvent();

            textBox.WriteText("");
            AssertError <IsRequiredError>(textBox);
            Assert.AreEqual(null, vm.NullableDoubleValue);
        }
Exemple #16
0
        private void GenerateHeader(Span addSpan, HtmlNode htmlNode)
        {
            try
            {
                string StringText = Process.ProcessItemTextFull(htmlNode.InnerText, false, false, true);
                if (!string.IsNullOrWhiteSpace(StringText))
                {
                    Binding FontSizeBinding = new Binding();
                    FontSizeBinding.Source = (StyleUpdater)Application.Current.Resources["StyleUpdater"];
                    FontSizeBinding.Path   = new PropertyPath("TextSizeLarge");

                    Span spanHeader = new Span();
                    BindingOperations.SetBinding(spanHeader, Span.FontSizeProperty, FontSizeBinding);
                    spanHeader.Inlines.Add(new Run()
                    {
                        Text = StringText, Foreground = new SolidColorBrush((Color)Application.Current.Resources["SystemAccentColor"])
                    });
                    spanHeader.Inlines.Add(new LineBreak());

                    addSpan.Inlines.Add(spanHeader);
                }
            }
            catch { }
        }
        public void WhenRequiredReactsOnInput()
        {
            var textBox = new TextBox {
                DataContext = new DummyViewModel {
                    NullableDoubleValue = 1
                }
            };
            var binding = new Binding
            {
                Path = new PropertyPath(DummyViewModel.NullableDoubleValuePropertyName),
                Mode = BindingMode.TwoWay
            };

            BindingOperations.SetBinding(textBox, Input.ValueProperty, binding);
            textBox.SetIsRequired(true);
            textBox.RaiseLoadedEvent();
            AssertNoError(textBox);

            textBox.WriteText("");
            AssertError <IsRequiredError>(textBox);

            textBox.WriteText("1");
            AssertNoError(textBox);
        }
 private PropertyItem(MediaElementWrapper wrapper, DependencyProperty property, DependencyProperty proxyProperty)
 {
     this.wrapper              = wrapper;
     this.mediaElement         = (MediaElement)MediaElementField.GetValue(wrapper);
     this.Property             = property;
     this.mediaElementProperty = typeof(MediaElement).GetProperty(property.Name);
     this.proxyProperty        = proxyProperty;
     if (property.ReadOnly)
     {
         var binding = new Binding(property.Name)
         {
             Source = wrapper, Mode = BindingMode.OneWay
         };
         BindingOperations.SetBinding(wrapper, this.proxyProperty, binding);
     }
     else
     {
         var binding = new Binding(property.Name)
         {
             Source = wrapper, Mode = BindingMode.TwoWay
         };
         BindingOperations.SetBinding(wrapper, this.proxyProperty, binding);
     }
 }
Exemple #19
0

        
Exemple #20
0

        
Exemple #21
0
        public static void ReceiveMarkupExtension(object targetObject, XamlSetMarkupExtensionEventArgs eventArgs)
        {
            var methodCallReaction = targetObject as MethodCallReaction;

            if (methodCallReaction == null)
            {
                return;
            }

            eventArgs.ThrowIfNull();
            eventArgs.MarkupExtension.ThrowIfNull();

            //reactiveSetter.ServiceProvider = eventArgs.ServiceProvider;

            if (eventArgs.Member.Name == "TargetObject")
            {
                // ReSharper disable once CanBeReplacedWithTryCastAndCheckForNull
                // ReSharper disable once UseNullPropagation
                if (eventArgs.MarkupExtension is Binding)
                {
                    var binding = (Binding)eventArgs.MarkupExtension;
                    if (binding.RelativeSource != null)
                    {
                        // TargetObject is being set to a Binding with a RelativeSource that
                        // relies on traversing the visual tree.
                        if (binding.RelativeSource.Mode == RelativeSourceMode.FindAncestor)
                        {
                            if (!methodCallReaction.IsAssociated)
                            {
                                //reactiveSetter.TargetObject = targetObject as DependencyObject;
                                methodCallReaction._eventArgs = eventArgs;
                                methodCallReaction._deferMarkupExtensionResolve = true;
                                //TODO eventArgs.Handled = true;?
                                return;
                            }
                            methodCallReaction.TargetObject = null;
                            methodCallReaction._eventArgs   = null;
                            methodCallReaction._deferMarkupExtensionResolve = false;

                            var frameworkElement = methodCallReaction.AssociatedObject as FrameworkElement;
                            if (frameworkElement == null)
                            {
                                throw new NotSupportedException();
                            }

                            var resolvedVisualAncestor = frameworkElement.FindParent(
                                binding.RelativeSource.AncestorType,
                                binding.RelativeSource.AncestorLevel);

                            var adjustedBinding = new Binding
                            {
                                Source = resolvedVisualAncestor,
                                Path   = binding.Path
                            };
                            BindingOperations.SetBinding(methodCallReaction, TargetObjectProperty, adjustedBinding);
                            eventArgs.Handled = true;
                        }
                    }
                }
                else if (eventArgs.MarkupExtension is StaticResourceExtension)
                {
                    var staticResourceExtension = (StaticResourceExtension)eventArgs.MarkupExtension;
                    var effectiveTargetObject   = staticResourceExtension.Reflect().Invoke <DependencyObject>(
                        ReflectionVisibility.InstanceNonPublic,
                        "ProvideValueInternal",
                        eventArgs.ServiceProvider, true);

                    if (effectiveTargetObject == null)
                    {
                        throw new NullReferenceException(
                                  "The provided value from the StaticResourceExtension " +
                                  $"\'{eventArgs.MarkupExtension.GetType().Name}\' is null.");
                    }

                    methodCallReaction.TargetObject = effectiveTargetObject;
                    eventArgs.Handled = true;
                }
                else if (eventArgs.MarkupExtension is DynamicResourceExtension)
                {
                    var dynamicResourceExtension = (DynamicResourceExtension)eventArgs.MarkupExtension;

                    var effectiveTargetObject = dynamicResourceExtension.Reflect().Invoke <DependencyObject>(
                        ReflectionVisibility.InstanceNonPublic,
                        "ProvideValueInternal",
                        eventArgs.ServiceProvider, true);

                    if (effectiveTargetObject == null)
                    {
                        throw new NullReferenceException(
                                  "The provided value from the DynamicResourceExtension " +
                                  $"\'{eventArgs.MarkupExtension.GetType().Name}\' is null.");
                    }

                    methodCallReaction.TargetObject = effectiveTargetObject;
                    eventArgs.Handled = true;
                }
                else
                {
                    var effectiveTargetObject = eventArgs.MarkupExtension.Reflect().Invoke <DependencyObject>(
                        ReflectionVisibility.InstanceNonPublic,
                        "ProvideValueInternal", eventArgs.ServiceProvider, true);

                    if (effectiveTargetObject == null)
                    {
                        throw new NotSupportedException(
                                  "The provided value from the MarkupExtension " +
                                  $"\'{eventArgs.MarkupExtension.GetType().Name}\' is null.");
                    }

                    methodCallReaction.TargetObject = effectiveTargetObject;
                    eventArgs.Handled = true;
                }
            }
        }
Exemple #22
0
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            this.dataGridControl = this.Template.FindName("PART_DataGridControl", this) as ModernDataGridControl;

            if (this.dataGridControl == null)
            {
                return;
            }

            //if (this.dataGridControl.Columns.Count == 0)
            {
                try
                {
#if DEBUG
                    this.dataGridControl.Columns.Add(new Column()
                    {
                        FieldName = CremaSchema.Index, Title = CremaSchema.Index,
                    });
#endif
                    this.dataGridControl.Columns.Add(new Column()
                    {
                        FieldName = CremaSchema.ID, Title = CremaSchema.ID,
                    });
                }
                catch
                {
                }
            }

            if (this.dataGridControl.AutoCreateColumns == false)
            {
                try
                {
                    var columnNames = new string[] { "tagColumn", "enableColumn", "modifierColumn", "modifiedDateTimeColumn", "creatorColumn", "createdDateTimeColumn" };
                    foreach (var item in columnNames)
                    {
                        if (this.TryFindResource(item) is ColumnBase column)
                        {
                            this.dataGridControl.Columns.Add(column);
                        }
                    }
                }
                catch
                {
                }
            }

            this.dataGridControl.RowDrag += DataGridControl_RowDrag;
            this.dataGridControl.RowDrop += DataGridControl_RowDrop;
            this.dataGridControl.ItemsSourceChangeCompleted += DataGridControl_ItemsSourceChangeCompleted;
            BindingOperations.SetBinding(this.viewSource, DataGridCollectionViewSource.SourceProperty, new Binding($"{nameof(Source)}.{nameof(CremaDataType.View)}")
            {
                Source = this,
            });
            BindingOperations.SetBinding(this.dataGridControl, ModernDataGridControl.ItemsSourceProperty, new Binding()
            {
                Source = this.viewSource,
            });
            BindingOperations.SetBinding(this.dataGridControl, ModernDataGridControl.IsVerticalScrollBarOnLeftSideProperty, new Binding(nameof(IsVerticalScrollBarOnLeftSide))
            {
                Source = this,
            });
            this.dataGridControl.IsDeleteCommandEnabled = true;
        }
Exemple #23
0
        public override Path CreatePath(List <Point> localPath, bool addBlurEffect)
        {
            // Create a StreamGeometry to use to specify myPath.
            var geometry = new StreamGeometry();

            using (StreamGeometryContext ctx = geometry.Open())
            {
                ctx.BeginFigure(localPath[0], true, true);

                // Draw a line to the next specified point.
                ctx.PolyLineTo(localPath, true, true);
            }

            // Freeze the geometry (make it unmodifiable)
            // for additional performance benefits.
            geometry.Freeze();

            // Create a path to draw a geometry with.
            var myPath = new Path();

            {
                // Specify the shape of the Path using the StreamGeometry.
                myPath.Data = geometry;

                if (addBlurEffect)
                {
                    var ef = new BlurEffect();
                    {
                        ef.KernelType    = KernelType.Gaussian;
                        ef.Radius        = 3.0;
                        ef.RenderingBias = RenderingBias.Performance;
                    }

                    myPath.Effect = ef;
                }

                var fillBrush = new SolidColorBrush();
                BindingOperations.SetBinding(fillBrush, SolidColorBrush.ColorProperty, new Binding("Variety.ClusterIndex")
                {
                    Converter = new IndexToColorConverter(), ConverterParameter = Colors.CornflowerBlue
                });
                var strokeBrush = new SolidColorBrush();
                BindingOperations.SetBinding(strokeBrush, SolidColorBrush.ColorProperty, new Binding("Color")
                {
                    Source = fillBrush, Converter = new ColorBrightnessConverter(), ConverterParameter = -0.15
                });

                myPath.Stroke             = strokeBrush;
                myPath.StrokeThickness    = 3;
                myPath.StrokeLineJoin     = PenLineJoin.Round;
                myPath.StrokeStartLineCap = PenLineCap.Triangle;
                myPath.StrokeEndLineCap   = PenLineCap.Square;

                myPath.Fill = fillBrush;

                myPath.Opacity          = 0.5;
                myPath.IsHitTestVisible = true;
                myPath.DataContext      = Region;
                myPath.Visibility       = Shape?.Visibility ?? Visibility.Visible;

                myPath.MouseEnter        += Shape_MouseEnter;
                myPath.MouseLeave        += Shape_MouseLeave;
                myPath.MouseLeftButtonUp += RegionHit_MouseLeftButtonUp;
            }
            return(myPath);
        }
        public RgbaParameterValue(OperatorPart[] valueHolders)
        {
            InitializeComponent();

            _rFloatEdit = new FloatParameterControl(valueHolders[0])
            {
                Precision = 2
            };
            Grid.SetColumn(_rFloatEdit, 0);
            XGrid.Children.Add(_rFloatEdit);
            _rFloatEdit.TabMoveEvent += TabMoveEventHandler;
            _parameterControls.Add(_rFloatEdit);

            _gFloatEdit = new FloatParameterControl(valueHolders[1])
            {
                Precision = 2
            };
            Grid.SetColumn(_gFloatEdit, 1);
            XGrid.Children.Add(_gFloatEdit);
            _gFloatEdit.TabMoveEvent += TabMoveEventHandler;
            _parameterControls.Add(_gFloatEdit);

            _bFloatEdit = new FloatParameterControl(valueHolders[2])
            {
                Precision = 2
            };
            Grid.SetColumn(_bFloatEdit, 2);
            XGrid.Children.Add(_bFloatEdit);
            _bFloatEdit.TabMoveEvent += TabMoveEventHandler;
            _parameterControls.Add(_bFloatEdit);

            _aFloatEdit = new FloatParameterControl(valueHolders[3])
            {
                Precision = 2
            };
            Grid.SetColumn(_aFloatEdit, 4);
            XGrid.Children.Add(_aFloatEdit);
            _aFloatEdit.TabMoveEvent += TabMoveEventHandler;
            _parameterControls.Add(_aFloatEdit);


            // Bind color fields
            var multiBinding = new MultiBinding {
                Converter = RgbToBrushConverter
            };

            multiBinding.Bindings.Add(new Binding("Value")
            {
                Source = _rFloatEdit
            });
            multiBinding.Bindings.Add(new Binding("Value")
            {
                Source = _gFloatEdit
            });
            multiBinding.Bindings.Add(new Binding("Value")
            {
                Source = _bFloatEdit
            });
            BindingOperations.SetBinding(XColorThumb, Border.BackgroundProperty, multiBinding);

            var binding = new Binding("Value")
            {
                Source = _aFloatEdit
            };

            XPatternOverlay.SetBinding(OpacityProperty, binding);


            Loaded   += RgbaParameterValue_Loaded;
            Unloaded += RgbaParameterValue_Unloaded;
        }
        public ColorSnapshot()
        {
            InitializeComponent();


            // Dynamically set background images for Buttons Screenshot, Home, Exit
            BitmapImage bi = new BitmapImage();

            bi.BeginInit();
            bi.UriSource = new Uri(@"Images\camera2.png", UriKind.Relative);
            bi.EndInit();

            snapshotBtn.Background          = new ImageBrush(bi);
            snapshotBtn.Height              = 150;
            snapshotBtn.Width               = 150;
            snapshotBtn.HorizontalAlignment = HorizontalAlignment.Center;
            snapshotBtn.VerticalAlignment   = VerticalAlignment.Bottom;
            snapshotBtn.ToolTip             = "Press to take a picture.";

            BitmapImage bi1 = new BitmapImage();

            bi1.BeginInit();
            bi1.UriSource = new Uri(@"Images\exit2.png", UriKind.Relative);
            bi1.EndInit();

            exitBtn.Background          = new ImageBrush(bi1);
            exitBtn.Height              = 100;
            exitBtn.Width               = 100;
            exitBtn.HorizontalAlignment = HorizontalAlignment.Right;
            exitBtn.VerticalAlignment   = VerticalAlignment.Bottom;
            exitBtn.ToolTip             = "Press to exit the application";

            BitmapImage bi2 = new BitmapImage();

            bi2.BeginInit();
            bi2.UriSource = new Uri(@"Images\Home-icon.png", UriKind.Relative);
            bi2.EndInit();

            homeBtn.Background          = new ImageBrush(bi2);
            homeBtn.Height              = 100;
            homeBtn.Width               = 100;
            homeBtn.HorizontalAlignment = HorizontalAlignment.Left;
            homeBtn.VerticalAlignment   = VerticalAlignment.Bottom;
            homeBtn.ToolTip             = "Press to return to Home Screen";

            BitmapImage bi3 = new BitmapImage();

            bi3.BeginInit();
            bi3.UriSource = new Uri(@"Images\save.png", UriKind.Relative);
            bi3.EndInit();

            saveBtn.Background          = new ImageBrush(bi3);
            saveBtn.Height              = 150;
            saveBtn.Width               = 150;
            saveBtn.HorizontalAlignment = HorizontalAlignment.Right;
            saveBtn.VerticalAlignment   = VerticalAlignment.Top;
            saveBtn.ToolTip             = "Save";
            saveBtn.Visibility          = Visibility.Hidden;
            saveBtn.Click              += new RoutedEventHandler(saveBtn_Click);

            BitmapImage bi4 = new BitmapImage();

            bi4.BeginInit();
            bi4.UriSource = new Uri(@"Images\delete.png", UriKind.Relative);
            bi4.EndInit();

            cancelBtn.Background          = new ImageBrush(bi4);
            cancelBtn.Height              = 150;
            cancelBtn.Width               = 150;
            cancelBtn.ToolTip             = "Delete";
            cancelBtn.HorizontalAlignment = HorizontalAlignment.Left;
            cancelBtn.VerticalAlignment   = VerticalAlignment.Top;
            cancelBtn.Visibility          = Visibility.Hidden;
            cancelBtn.Click              += new RoutedEventHandler(cancelBtn_Click);

            this.sensorChooser = new KinectSensorChooser();
            this.sensorChooser.KinectChanged        += SensorChooserOnKinectChanged;
            this.sensorChooserUi.KinectSensorChooser = this.sensorChooser;
            this.sensorChooser.Start();

            // Bind the sensor chooser's current sensor to the KinectRegion
            var regionSensorBinding = new Binding("Kinect")
            {
                Source = this.sensorChooser
            };

            BindingOperations.SetBinding(this.kinectRegion, KinectRegion.KinectSensorProperty, regionSensorBinding);
        }
        public async Task EventSenderTestCore(bool addControlFirst, bool linearLayout)
        {
            Grid   rootRoot = new Grid();
            Grid   root     = new Grid();
            Button bt       = null;

            if (addControlFirst)
            {
                if (linearLayout)
                {
                    bt = new TestButton()
                    {
                        Name = "bt"
                    };
                    root.Children.Add(bt);
                }
                else
                {
                    bt = new TestButton()
                    {
                        Name = "bt"
                    };
                    rootRoot.Children.Add(bt);
                    rootRoot.Children.Add(root);
                }
            }

            EventToCommandTestClass eventToCommand1 = new EventToCommandTestClass()
            {
                EventName = "SizeChanged"
            };
            EventToCommandTestClass eventToCommand2 = new EventToCommandTestClass()
            {
                EventName = "SizeChanged"
            };

            BindingOperations.SetBinding(eventToCommand2, EventToCommand.SourceObjectProperty, new Binding()
            {
                ElementName = "bt"
            });
            EventToCommandTestClass eventToCommand3 = new EventToCommandTestClass()
            {
                EventName = "SizeChanged", SourceName = "bt"
            };

            EventToCommandTestClass eventToCommand4 = new EventToCommandTestClass()
            {
                EventName = "Loaded"
            };
            EventToCommandTestClass eventToCommand5 = new EventToCommandTestClass()
            {
                EventName = "Loaded"
            };

            BindingOperations.SetBinding(eventToCommand5, EventToCommand.SourceObjectProperty, new Binding()
            {
                ElementName = "bt"
            });
            EventToCommandTestClass eventToCommand6 = new EventToCommandTestClass()
            {
                EventName = "Loaded", SourceName = "bt"
            };

            Interaction.GetBehaviors(root).Add(eventToCommand1);
            Interaction.GetBehaviors(root).Add(eventToCommand2);
            Interaction.GetBehaviors(root).Add(eventToCommand3);
            Interaction.GetBehaviors(root).Add(eventToCommand4);
            Interaction.GetBehaviors(root).Add(eventToCommand5);
            Interaction.GetBehaviors(root).Add(eventToCommand6);

            if (!addControlFirst)
            {
                if (linearLayout)
                {
                    bt = new TestButton()
                    {
                        Name = "bt"
                    };
                    root.Children.Add(bt);
                }
                else
                {
                    bt = new TestButton()
                    {
                        Name = "bt"
                    };
                    rootRoot.Children.Add(bt);
                    rootRoot.Children.Add(root);
                }
            }
            bt.Loaded      += bt_Loaded;
            bt.SizeChanged += bt_SizeChanged;
            if (linearLayout)
            {
                Window.Content = root;
            }
            else
            {
                Window.Content = rootRoot;
            }
            await EnqueueShowWindow();

            EnqueueWindowUpdateLayout();
            EnqueueCallback(() => {
                Assert.AreEqual(1, eventToCommand1.EventCount);
                Assert.AreEqual(root, eventToCommand1.EventSender);
                Assert.AreEqual(EventToCommandType.AssociatedObject, eventToCommand1.Type);

                Assert.IsTrue(eventToCommand2.EventCount > 0);
                Assert.AreEqual(bt, eventToCommand2.EventSender);
                Assert.AreEqual(EventToCommandType.SourceObject, eventToCommand2.Type);

                Assert.AreEqual(1, eventToCommand3.EventCount);
                Assert.AreEqual(bt, eventToCommand3.EventSender);
                Assert.AreEqual(EventToCommandType.SourceName, eventToCommand3.Type);

                Assert.AreEqual(1, eventToCommand4.EventCount);
                Assert.AreEqual(root, eventToCommand4.EventSender);
                Assert.AreEqual(EventToCommandType.AssociatedObject, eventToCommand4.Type);

                Assert.AreEqual(1, eventToCommand5.EventCount);
                Assert.AreEqual(bt, eventToCommand5.EventSender);
                Assert.AreEqual(EventToCommandType.SourceObject, eventToCommand5.Type);

                Assert.AreEqual(1, eventToCommand6.EventCount);
                Assert.AreEqual(bt, eventToCommand6.EventSender);
                Assert.AreEqual(EventToCommandType.SourceName, eventToCommand6.Type);
            });
            EnqueueTestComplete();
        }
        void Q554072_1Core(string eventName)
        {
#else
        async Task Q554072_1Core(string eventName)
        {
#endif
            var control = new Grid();
            var bt      = new Button()
            {
                Name = "View"
            };
            control.Children.Add(bt);
            int counter1 = 0;
            int counter2 = 0;
            int counter3 = 0;
            control.Loaded += (d, e) => counter1++;
            var eventToCommand1 = new EventToCommand()
            {
                PassEventArgsToCommand = true,
                EventName  = eventName,
                Command    = new DelegateCommand(() => counter2++),
                SourceName = "View",
            };
            var eventToCommand2 = new EventToCommand()
            {
                PassEventArgsToCommand = true,
                EventName  = eventName,
                Command    = new DelegateCommand(() => counter3++),
                SourceName = "View",
            };
            Interaction.GetBehaviors(control).Add(eventToCommand1);
            Interaction.GetBehaviors(bt).Add(eventToCommand2);
            Window.Content = control;
#if NETFX_CORE
            await
#endif
            EnqueueShowWindow();
            EnqueueCallback(() => {
                Assert.AreEqual(counter2, counter1);
                Assert.AreEqual(counter3, counter1);
            });
            EnqueueTestComplete();
        }

#if !NETFX_CORE
        void Q554072_2Core(string eventName)
        {
#else
        async Task Q554072_2Core(string eventName)
        {
#endif
            var control = new Grid();
            var bt      = new Button()
            {
                Name = "View"
            };
            control.Children.Add(bt);
            int counter1 = 0;
            int counter2 = 0;
            control.Loaded += (d, e) => counter1++;
            var eventToCommand1 = new EventToCommand()
            {
                PassEventArgsToCommand = true,
                EventName = eventName,
                Command   = new DelegateCommand(() => counter2++),
            };
            BindingOperations.SetBinding(eventToCommand1, EventToCommand.SourceObjectProperty, new Binding()
            {
                ElementName = "View"
            });
            Interaction.GetBehaviors(control).Add(eventToCommand1);
            Window.Content = control;
#if NETFX_CORE
            await
#endif
            EnqueueShowWindow();
            EnqueueCallback(() => {
                var evv = eventToCommand1.SourceObject;
                Assert.AreEqual(counter2, counter1);
            });
            EnqueueTestComplete();
        }

        [Test, Asynchronous]
            public Segment(PlotVisualizationObjectView <TPlotVisualizationObject, TData> parent)
            {
                this.parent = parent;

                this.lineFigure   = new PathFigure();
                this.lineGeometry = new PathGeometry()
                {
                    Transform = parent.TransformGroup
                };
                this.lineGeometry.Figures.Add(this.lineFigure);
                this.LinePath = new Path()
                {
                    Data = this.lineGeometry
                };

                this.markerGeometry = new PathGeometry()
                {
                    Transform = parent.TransformGroup
                };
                this.MarkerPath = new Path()
                {
                    StrokeThickness = 1, Data = this.markerGeometry
                };
                this.ClearMarkers();

                this.rangeFigure   = new PathFigure();
                this.rangeGeometry = new PathGeometry()
                {
                    Transform = parent.TransformGroup
                };
                this.rangeGeometry.Figures.Add(this.rangeFigure);
                this.RangePath = new Path()
                {
                    StrokeThickness = 1, Data = this.rangeGeometry
                };

                // Create bindings for lines
                var binding = new Binding(nameof(parent.VisualizationObject.Color))
                {
                    Source    = parent.VisualizationObject,
                    Converter = new Converters.ColorConverter(),
                };

                BindingOperations.SetBinding(this.LinePath, Shape.StrokeProperty, binding);

                binding = new Binding(nameof(parent.VisualizationObject.LineWidth))
                {
                    Source = parent.VisualizationObject,
                };
                BindingOperations.SetBinding(this.LinePath, Shape.StrokeThicknessProperty, binding);

                // Create bindings for markers
                binding = new Binding(nameof(parent.VisualizationObject.MarkerColor))
                {
                    Source    = parent.VisualizationObject,
                    Converter = new Converters.ColorConverter(),
                };
                BindingOperations.SetBinding(this.MarkerPath, Shape.StrokeProperty, binding);

                // Create bindings for ranges
                binding = new Binding(nameof(parent.VisualizationObject.RangeColor))
                {
                    Source    = parent.VisualizationObject,
                    Converter = new Converters.ColorConverter(),
                };
                BindingOperations.SetBinding(this.RangePath, Shape.StrokeProperty, binding);

                binding = new Binding(nameof(parent.VisualizationObject.RangeWidth))
                {
                    Source = parent.VisualizationObject,
                };
                BindingOperations.SetBinding(this.RangePath, Shape.StrokeThicknessProperty, binding);

                this.previousPointIsValid = false;
            }
Exemple #29
0
#pragma warning restore CA1000 // Do not declare static members on generic types

        #endregion

        #region Internal Static Methods

        internal static object ProvideValue(
            DependencyObject target,
            DependencyProperty property,
            object defaultValue,
            BindingBase xamlBinding)
        {
            if (target == null ||
                property == null)
            {
                return(null);
            }
            object outputValue = defaultValue;

            if (outputValue == null ||
                string.IsNullOrEmpty(outputValue.ToString()))
            {
                throw new InvalidOperationException($@"No default value provided for property ""{target}.{property.Name}""");
            }
            if (!outputValue.GetType().IsSerializable)
            {
                throw new InvalidOperationException($@"Default value provided for property ""{target}.{property.Name}"" is not serializable");
            }

            FrameworkElement visualAnchor = AbstractPropertyState <TState, TElement, TProperty> .GetVisualAnchor(target);

            if (!(target is FrameworkElement element) || visualAnchor != null)
            {
                element = visualAnchor;
            }
            var defaultString = outputValue as string;

            if (!string.IsNullOrEmpty(defaultString))
            {
                outputValue = AbstractPropertyState <TState, TElement, TProperty> .ConvertFromString(target.GetType(), property, defaultString);
            }
            var propertyMultiValueConverter = new PropertyMultiValueConverter()
            {
                Target   = element,
                Property = property,
            };

            void handler(object s, RoutedEventArgs e)
            {
                if (element != null)
                {
                    element.Loaded -= handler;
                }

                if (xamlBinding != null &&
                    !IsPropertyPersisted(target, property))
                {
                    // Normally the persisted state is the initial value used
                    // for an element property when the UI is rendered, but if
                    // no value is persisted (and a data bound property is present)
                    // then use the data bound value.
                    propertyMultiValueConverter.PropertyValuePreference = PropertyValuePreference.DataBound;
                }
                if (!HasPropertyValue(target, property))
                {
                    object value = AddPropertyValue(target, property, outputValue);
                    if (value == null)
                    {
                        throw new InvalidOperationException($@"The element ""{target}"" has no unique identifier for property persistence");
                    }
                }

                var multiBinding = new MultiBinding()
                {
                    Converter           = propertyMultiValueConverter,
                    Mode                = BindingMode.TwoWay,
                    UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged,
                };

                // Add a new binding between the element property and the
                // persisted state.
                multiBinding.Bindings.Add(CreateStateBinding(target, property));
                if (xamlBinding != null)
                {
                    // If the element property was previously data bound in XAML
                    // then add that binding to the multibinding collection.
                    multiBinding.Bindings.Add(xamlBinding);
                }
                BindingOperations.SetBinding(target, property, multiBinding);

                if (element.IsLoaded)
                {
                    propertyMultiValueConverter.PropertyValuePreference = PropertyValuePreference.DataBound;
                }
            }

            // Windows are already loaded when the application starts
            // so need to invoke their loaded handlers manually.
            if (target is Window)
            {
                handler(null, null);
            }
            // Keep track of the loaded handlers in case they need to
            // activated manually later.
            AddPropertyLoadedHandler(target, property, handler);
            if (element != null)
            {
                element.Loaded += handler;
            }
            if (HasPropertyValue(target, property))
            {
                return(GetPropertyValue(target, property));
            }
            return(outputValue);
        }
        private Inline ImageInlineEvaluator(Match match)
        {
            if (match == null)
            {
                throw new ArgumentNullException("match");
            }

            string      linkText  = match.Groups[2].Value;
            string      url       = match.Groups[3].Value;
            BitmapImage imgSource = null;

            try
            {
                if (!Uri.IsWellFormedUriString(url, UriKind.Absolute) && !System.IO.Path.IsPathRooted(url))
                {
                    url = System.IO.Path.Combine(AssetPathRoot ?? string.Empty, url);
                }

                imgSource = new BitmapImage(new Uri(url, UriKind.RelativeOrAbsolute));
            }
            catch (Exception)
            {
                return(new Run("!" + url)
                {
                    Foreground = Brushes.Red
                });
            }

            Image image = new Image {
                Source = imgSource, Tag = linkText
            };

            if (ImageStyle == null)
            {
                image.Margin = new Thickness(0);
            }
            else
            {
                image.Style = ImageStyle;
            }

            // Bind size so document is updated when image is downloaded
            if (imgSource.IsDownloading)
            {
                Binding binding = new Binding(nameof(BitmapImage.Width));
                binding.Source = imgSource;
                binding.Mode   = BindingMode.OneWay;

                BindingExpressionBase bindingExpression        = BindingOperations.SetBinding(image, Image.WidthProperty, binding);
                EventHandler          downloadCompletedHandler = null;
                downloadCompletedHandler = (sender, e) =>
                {
                    imgSource.DownloadCompleted -= downloadCompletedHandler;
                    bindingExpression.UpdateTarget();
                };
                imgSource.DownloadCompleted += downloadCompletedHandler;
            }
            else
            {
                image.Width = imgSource.Width;
            }

            return(new InlineUIContainer(image));
        }