示例#1
0
        protected internal virtual void SetupDisplayMemberBinding(DataGridContext dataGridContext)
        {
            // Bind the cell content.
            var column = this.ParentColumn as Column;

            if (column != null)
            {
                var displayMemberBinding = default(BindingBase);
                var dataItem             = this.ParentRow.DataContext;

                // If the dataContext is our ParentRow, we do not create any binding
                if (dataItem != this.ParentRow)
                {
                    displayMemberBinding = column.GetDisplayMemberBinding();

                    if (displayMemberBinding == null)
                    {
                        if (dataGridContext == null)
                        {
                            throw new InvalidOperationException("An attempt was made to create a DisplayMemberBinding before the DataGridContext has been initialized.");
                        }

                        if (!DesignerProperties.GetIsInDesignMode(this))
                        {
                            var propertyDescription = ItemsSourceHelper.CreateOrGetPropertyDescriptionFromColumn(dataGridContext, column, (dataItem != null) ? dataItem.GetType() : null);
                            ItemsSourceHelper.UpdateColumnFromPropertyDescription(column, dataGridContext.DataGridControl.DefaultCellEditors, dataGridContext.AutoCreateForeignKeyConfigurations, propertyDescription);

                            displayMemberBinding = column.GetDisplayMemberBinding();
                        }

                        column.IsBindingAutoCreated = true;
                    }
                }

                if (displayMemberBinding != null)
                {
                    m_canBeRecycled = DataCell.VerifyDisplayMemberBinding(displayMemberBinding);

                    BindingOperations.SetBinding(this, Cell.ContentProperty, displayMemberBinding);

                    var xmlElement = this.GetValue(Cell.ContentProperty) as XmlElement;
                    if (xmlElement != null)
                    {
                        // Convert binding to an InnerXML binding in the case we are bound on a XmlElement
                        // to be able to refresh the data in the XML.

                        //under any circumstances, a cell that is bound to XML cannot be recycled
                        m_canBeRecycled = false;

                        this.ClearDisplayMemberBinding();

                        var xmlElementBinding = new Binding("InnerXml");
                        xmlElementBinding.Source = xmlElement;
                        xmlElementBinding.Mode   = BindingMode.TwoWay;
                        xmlElementBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;

                        BindingOperations.SetBinding(this, Cell.ContentProperty, xmlElementBinding);
                    }
                }
                else
                {
                    this.ClearDisplayMemberBinding();
                }
            }
            else
            {
                this.ClearDisplayMemberBinding();
            }
        }
示例#2
0
 public static bool IsInDesignMode(this FrameworkElement el)
 {
     return(DesignerProperties.GetIsInDesignMode(el));
 }
示例#3
0
        private void TrimText()
        {
            var textBlock = (TextBlock)this.Content;

            if (textBlock == null)
            {
                return;
            }

            if (DesignerProperties.GetIsInDesignMode(textBlock))
            {
                return;
            }

            var freeSize = _constraint.Width
                           - this.Padding.Left
                           - this.Padding.Right
                           - textBlock.Margin.Left
                           - textBlock.Margin.Right;

            // ReSharper disable once CompareOfFloatsByEqualityOperator
            if (freeSize <= 0)
            {
                return;
            }

            using (this.BlockTextChangedEvent())
            {
                // this actually sets textBlock's text back to its original value
                var desiredSize = TextBlockTrimmer.MeasureString(textBlock, _originalText);

                if (desiredSize <= freeSize)
                {
                    return;
                }

                var ellipsisSize = TextBlockTrimmer.MeasureString(textBlock, ELLIPSIS);
                freeSize -= ellipsisSize;
                var epsilon = ellipsisSize / 3;

                if (freeSize < epsilon)
                {
                    textBlock.Text = _originalText;
                    return;
                }

                var segments = new List <string>();

                var builder = new StringBuilder();

                switch (this.EllipsisPosition)
                {
                case EllipsisPosition.End:
                    TextBlockTrimmer.TrimText(textBlock, _originalText, freeSize, segments, epsilon, false);
                    foreach (var segment in segments)
                    {
                        builder.Append(segment);
                    }
                    builder.Append(ELLIPSIS);
                    break;

                case EllipsisPosition.Start:
                    TextBlockTrimmer.TrimText(textBlock, _originalText, freeSize, segments, epsilon, true);
                    builder.Append(ELLIPSIS);
                    foreach (var segment in ((IEnumerable <string>)segments).Reverse())
                    {
                        builder.Append(segment);
                    }
                    break;

                case EllipsisPosition.Middle:
                    var textLength = _originalText.Length / 2;
                    var firstHalf  = _originalText.Substring(0, textLength);
                    var secondHalf = _originalText.Substring(textLength);

                    freeSize /= 2;

                    TextBlockTrimmer.TrimText(textBlock, firstHalf, freeSize, segments, epsilon, false);
                    foreach (var segment in segments)
                    {
                        builder.Append(segment);
                    }
                    builder.Append(ELLIPSIS);

                    segments.Clear();

                    TextBlockTrimmer.TrimText(textBlock, secondHalf, freeSize, segments, epsilon, true);
                    foreach (var segment in ((IEnumerable <string>)segments).Reverse())
                    {
                        builder.Append(segment);
                    }
                    break;

                default:
                    throw new NotSupportedException();
                }

                textBlock.Text = builder.ToString();
            }
        }
示例#4
0
 public OxySKElement()
 {
     this.designMode = DesignerProperties.GetIsInDesignMode(this);
     RenderOptions.SetBitmapScalingMode(this, BitmapScalingMode.NearestNeighbor);
 }
示例#5
0
        public override void OnApplyTemplate()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            var expression = BindingOperations.GetBindingExpression(this, TextProperty);

            if (expression.IsEmpty())
            {
                return;
            }

            var binding = BindingOperations.GetBinding(this, TextProperty);

            if (binding.IsEmpty())
            {
                return;
            }

            var newBinding = new Binding(binding.Path.Path)
            {
                Mode = binding.Mode,
                NotifyOnValidationError = true,
                UpdateSourceTrigger     = UpdateSourceTrigger.Explicit,
                ConverterCulture        = CultureInfo.CurrentCulture,
            };

            var x = this.DataContext?.GetType().GetProperty(expression.ParentBinding?.Path.Path);

            if (x == null)
            {
                return;
            }
            switch (x.PropertyType)
            {
            case Type intType when intType == typeof(int):
                this.Format = expression.ParentBinding.StringFormat;
                if (this.Format.IsEmpty())
                {
                    this.Format = "#,0";
                }
                newBinding.Converter = new StringToIntegerConverter();
                break;

            case Type intType when intType == typeof(int?):
                this.Format = expression.ParentBinding.StringFormat;
                if (this.Format.IsEmpty())
                {
                    this.Format = "#,0";
                }
                newBinding.Converter = new StringToNullableIntegerConverter();
                break;

            case Type intType when intType == typeof(decimal):
                this.Format = expression.ParentBinding.StringFormat;
                if (this.Format.IsEmpty())
                {
                    this.Format = "#,0.00";
                }
                newBinding.Converter = new StringToDecimalConverter();
                break;

            case Type intType when intType == typeof(decimal?):
                this.Format = expression.ParentBinding.StringFormat;
                if (this.Format.IsEmpty())
                {
                    this.Format = "#,0.00";
                }
                newBinding.Converter = new StringToNullableDecimalConverter();
                break;

            default:
                break;
            }
            newBinding.ConverterParameter = this.Format;
            newBinding.StringFormat       = this.Format;
            BindingOperations.SetBinding(this, TextProperty, newBinding);

            base.OnApplyTemplate();
        }
示例#6
0
 public SKElement()
 {
     designMode = DesignerProperties.GetIsInDesignMode(this);
 }
示例#7
0
        public ExamViewModel()
        {
            if (!DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject()))
            {
                svc          = new OnsiteServices();
                CurrentSheet = new ExamSheetResponse();
                CurrentSheet = TestingData.sheet;
                IsTimpUp     = false;
                State        = TestingData.State;


                BorderColor = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromRgb(0, 0, 0));

                First = new ChoiceViewModel {
                    Callback = SetCurrentChoice
                };
                Second = new ChoiceViewModel {
                    Callback = SetCurrentChoice
                };
                Third = new ChoiceViewModel {
                    Callback = SetCurrentChoice
                };
                Fourth = new ChoiceViewModel {
                    Callback = SetCurrentChoice
                };
                QuestionSelect = new QuestionViewModel {
                    Callback = SetQPreview
                };

                ChoiceSelect = new ChoiceSelector();

                SelectIndex = 0;

                currentQuestionNo = 1;
                CurrentAnswer     = new Answer();
                Answers           = new List <Answer>();
                InitializeAnswers();
                //MainExamVisibility = Visibility.Collapsed;

                //ExamAns = new ExamAnsViewModel();
                //ExamAns.Answers = Answers;
                QuestionSelect = new QuestionViewModel();

                #region TimeCal
                if (TestingData.State != "CheckAnswer" && this.IsTimpUp == false)
                {
                    Duration        = new TimeSpan(0, 0, TestingData.TestDuration);
                    DisplayDuration = Duration.ToString();
                    Timer           = new DispatcherTimer
                    {
                        Interval = TimeSpan.FromSeconds(1)
                    };
                    Timer.Tick += (sndr, se) =>
                    {
                        if (Duration <= new TimeSpan(0, 0, 0))
                        {
                            SendResult();
                            if (this.IsTimpUp)
                            {
                                SendResultEvent(this, new Models.SendResultArgs {
                                    IsTimeUp = true
                                });
                                this.IsTimpUp = false;
                            }
                        }
                        Duration = Duration.Subtract(TimeSpan.FromSeconds(1));
                        TestingData.TestDuration = (int)Duration.TotalSeconds;
                        DisplayDuration          = Duration.ToString();
                    };
                    Timer.Start();
                }
                #endregion TimeCal

                ProfilePhoto         = TestingData.ProfilePhoto;
                FullName             = TestingData.sheet.FirstName + "  " + TestingData.sheet.LastName;
                SubjectName          = TestingData.sheet.SubjectName;
                TestingData.Activity = StudentActivity.Testing; // ART

                //if (Answers.Count() == 0)
                //{
                //    InitializeAnswers();
                //}

                //set current question  choice
                SetCurrentQuestion(currentQuestionNo);

                MainExamVisibility  = Visibility.Visible;
                ExamAnsVisibility   = Visibility.Collapsed;
                SendExamVisibility  = Visibility.Collapsed;
                AlertResult         = Visibility.Collapsed;
                BtnChooseVisibility = Visibility.Collapsed;
            }
        }
        public ViewModelLocatorBase()
        {
#if WPF
            _designMode = DesignerProperties.GetIsInDesignMode(new DependencyObject());
#endif
        }
示例#9
0
 public static bool IsDesignMode(this DependencyObject obj)
 {
     return(DesignerProperties.GetIsInDesignMode(obj));
 }
示例#10
0
 private bool IsInDesignMode()
 {
     return(DesignerProperties.GetIsInDesignMode(dummy));
 }
示例#11
0
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string text;

            // Return the text key only in design mode. Nothing better to do for now.
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                switch (relKind)
                {
                case RelativeTimeKind.None:
                    text = Tx.Time(DateTime.Now, details);
                    break;

                case RelativeTimeKind.PointInTime:
                    text = Tx.RelativeTime(DateTime.Now.AddHours(2).AddMinutes(34));
                    break;

                case RelativeTimeKind.CurrentTimeSpan:
                    text = Tx.TimeSpan(DateTime.Now.AddHours(2).AddMinutes(34));
                    break;

                case RelativeTimeKind.TimeSpan:
                    text = Tx.TimeSpan(TimeSpan.FromHours(2) + TimeSpan.FromMinutes(34));
                    break;

                default:
                    text = "{Error: Invalid relKind}";                               // Should not happen
                    break;
                }
            }
            else
            {
                // values[0] is the dictionary Dummy binding, don't use it
                // values[1] is the timer Dummy binding, don't use it

                // Read the time value from binding number three.
                if (values[2] == DependencyProperty.UnsetValue)
                {
                    return(DependencyProperty.UnsetValue);
                }

                DateTime ConvertToDateTime(object obj) =>
                obj is DateTimeOffset dtos ? dtos.LocalDateTime : System.Convert.ToDateTime(obj);

                DateTime dt;
                TimeSpan ts;
                switch (relKind)
                {
                case RelativeTimeKind.None:
                    dt   = ConvertToDateTime(values[2]);
                    text = Tx.Time(dt, details);
                    break;

                case RelativeTimeKind.PointInTime:
                    dt   = ConvertToDateTime(values[2]);
                    text = Tx.RelativeTime(dt);
                    break;

                case RelativeTimeKind.CurrentTimeSpan:
                    dt   = ConvertToDateTime(values[2]);
                    text = Tx.TimeSpan(dt);
                    break;

                case RelativeTimeKind.TimeSpan:
                    if (values[2] is TimeSpan)
                    {
                        ts   = (TimeSpan)values[2];
                        text = Tx.TimeSpan(ts);
                    }
                    else
                    {
                        text = "";
                    }
                    break;

                default:
                    text = "{Error: Invalid relKind}";                               // Should not happen
                    break;
                }
            }

            if (upperCase)
            {
                text = Tx.UpperCase(text);
            }

            return(text);
        }
示例#12
0
        protected override void OnInitialized(EventArgs e)
        {
            var designMode = DesignerProperties.GetIsInDesignMode(this);

            string libVlcPath   = null;
            var    libVlcOption = VlcOption;

            if (LibVlcPath != null)
            {
                libVlcPath = Path.IsPathRooted(LibVlcPath)
                    ? LibVlcPath
                    : Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)
                             .CombinePath(LibVlcPath);
            }

            if (!designMode)
            {
                if (libVlcPath != null)
                {
                    if (libVlcOption == null)
                    {
                        Initialize(libVlcPath);
                    }
                    else
                    {
                        Initialize(libVlcPath, libVlcOption);
                    }
                }
                else
                {
                    var vlcSettings =
                        Assembly.GetEntryAssembly()
                        .GetCustomAttributes(typeof(VlcSettingsAttribute), false);

                    if (vlcSettings.Length > 0)
                    {
                        var vlcSettingsAttribute = vlcSettings[0] as VlcSettingsAttribute;

                        if (vlcSettingsAttribute != null && vlcSettingsAttribute.LibVlcPath != null)
                        {
                            libVlcPath = Path.IsPathRooted(vlcSettingsAttribute.LibVlcPath)
                                ? vlcSettingsAttribute.LibVlcPath
                                : Path.GetDirectoryName(
                                Process.GetCurrentProcess().MainModule.FileName)
                                         .CombinePath(vlcSettingsAttribute.LibVlcPath);
                        }

                        if (vlcSettingsAttribute != null && vlcSettingsAttribute.VlcOption != null)
                        {
                            libVlcOption = vlcSettingsAttribute.VlcOption;
                        }
                    }

                    Initialize(libVlcPath, libVlcOption);
                }
            }

            if (VisualParent == null)
            {
            }
            else
            {
                Loaded += OnLoaded;
            }

            base.OnInitialized(e);
        }
示例#13
0
 /// <summary>
 /// Determines whether this dependency object is running in design mode.
 /// </summary>
 /// <param name="obj">The object.</param>
 internal static bool IsInDesignMode(this System.Windows.DependencyObject obj)
 {
     return(DesignerProperties.GetIsInDesignMode(obj));
 }
示例#14
0
 public VirtualScrollPanel()
 {
     if (!DesignerProperties.GetIsInDesignMode(this))
         Dispatcher.BeginInvoke(new Action(Initialize));
 }
示例#15
0
        private static void InitAnimationOrImage(Image imageControl)
        {
            var controller = GetAnimationController(imageControl);

            if (controller != null)
            {
                controller.Dispose();
            }
            SetAnimationController(imageControl, null);
            SetIsAnimationLoaded(imageControl, false);

            BitmapSource source              = GetAnimatedSource(imageControl) as BitmapSource;
            bool         isInDesignMode      = DesignerProperties.GetIsInDesignMode(imageControl);
            bool         animateInDesignMode = GetAnimateInDesignMode(imageControl);
            bool         shouldAnimate       = !isInDesignMode || animateInDesignMode;

            // For a BitmapImage with a relative UriSource, the loading is deferred until
            // BaseUri is set. This method will be called again when BaseUri is set.
            bool isLoadingDeferred = IsLoadingDeferred(source);

            if (source != null && shouldAnimate && !isLoadingDeferred)
            {
                // Case of image being downloaded: retry after download is complete
                if (source.IsDownloading)
                {
                    EventHandler handler = null;
                    handler = (sender, args) =>
                    {
                        source.DownloadCompleted -= handler;
                        InitAnimationOrImage(imageControl);
                    };
                    source.DownloadCompleted += handler;
                    imageControl.Source       = source;
                    return;
                }

                var animation = GetAnimation(imageControl, source);
                if (animation != null)
                {
                    if (animation.KeyFrames.Count > 0)
                    {
                        // For some reason, it sometimes throws an exception the first time... the second time it works.
                        TryTwice(() => imageControl.Source = (ImageSource)animation.KeyFrames[0].Value);
                    }
                    else
                    {
                        imageControl.Source = source;
                    }

                    controller = new ImageAnimationController(imageControl, animation, GetAutoStart(imageControl));
                    SetAnimationController(imageControl, controller);
                    SetIsAnimationLoaded(imageControl, true);
                    imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl));
                    return;
                }
            }
            imageControl.Source = source;
            if (source != null)
            {
                SetIsAnimationLoaded(imageControl, true);
                imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl));
            }
        }
示例#16
0
        protected internal virtual void SetupDisplayMemberBinding(DataGridContext dataGridContext)
        {
            // Bind the cell content.
            Column column = this.ParentColumn as Column;

            if (column != null)
            {
                BindingBase displayMemberBinding = null;
                object      dataContext          = this.ParentRow.DataContext;

                // If the dataContext is our ParentRow, we do not create any binding
                if (dataContext != this.ParentRow)
                {
                    // Disable warning for DisplayMemberBinding when internaly used
#pragma warning disable 618

                    displayMemberBinding = column.DisplayMemberBinding;

#pragma warning restore 618


                    if (displayMemberBinding == null)
                    {
                        if ((dataGridContext == null) || (dataGridContext.ItemsSourceFieldDescriptors == null))
                        {
                            throw new InvalidOperationException("An attempt was made to create a DisplayMemberBinding before the DataGridContext has been initialized.");
                        }

                        if (!DesignerProperties.GetIsInDesignMode(this))
                        {
                            bool isDataGridUnboundItemProperty;

                            displayMemberBinding = ItemsSourceHelper.AutoCreateDisplayMemberBinding(
                                column, dataGridContext, dataContext, out isDataGridUnboundItemProperty);

                            column.IsBoundToDataGridUnboundItemProperty = isDataGridUnboundItemProperty;
                        }

                        // Disable warning for DisplayMemberBinding when internaly used
#pragma warning disable 618
                        column.DisplayMemberBinding = displayMemberBinding;
#pragma warning restore 618

                        //mark the Column's Binding as AutoCreated.
                        column.IsBindingAutoCreated = true;
                    }
                }

                if (displayMemberBinding != null)
                {
                    m_canBeRecycled = DataCell.VerifyDisplayMemberBinding(displayMemberBinding);

                    BindingOperations.SetBinding(this, Cell.ContentProperty, displayMemberBinding);

                    XmlElement xmlElement =
                        this.GetValue(Cell.ContentProperty) as XmlElement;

                    if (xmlElement != null)
                    {
                        // Convert binding to an InnerXML binding in the case we are bound on a XmlElement
                        // to be able to refresh the data in the XML.

                        //under any circumstances, a cell that is bound to XML cannot be recycled
                        m_canBeRecycled = false;

                        BindingOperations.ClearBinding(this, Cell.ContentProperty);
                        this.ClearValue(Cell.ContentProperty);

                        Binding xmlElementBinding = new Binding("InnerXml");
                        xmlElementBinding.Source = xmlElement;
                        xmlElementBinding.Mode   = BindingMode.TwoWay;
                        xmlElementBinding.UpdateSourceTrigger = UpdateSourceTrigger.Explicit;

                        BindingOperations.SetBinding(this, Cell.ContentProperty, xmlElementBinding);
                    }
                }
            }
        }
示例#17
0
 private static bool IsInDesignMode(DependencyObject element)
 {
     return(DesignerProperties.GetIsInDesignMode(element));
 }
示例#18
0
 /// <summary>
 /// 获取指定元素是否为设计模式。
 /// </summary>
 /// <param name="element"></param>
 /// <returns></returns>
 public static bool GetIsInDesignTool(DependencyObject element)
 {
     return(DesignerProperties.GetIsInDesignMode(element));
 }
示例#19
0
        /// <summary>
        /// Overridden measure. It calculates a size where all of
        /// of the vertices are visible.
        /// </summary>
        /// <param name="constraint">The size constraint.</param>
        /// <returns>The calculated size.</returns>
        protected override Size MeasureOverride(Size constraint)
        {
            var oldSize = ContentSize;

            _topLeft     = new Point(double.PositiveInfinity, double.PositiveInfinity);
            _bottomRight = new Point(double.NegativeInfinity, double.NegativeInfinity);

            foreach (UIElement child in InternalChildren)
            {
                //measure the child
                child.Measure(constraint);

                //get the position of the vertex
                var left = GetFinalX(child);
                var top  = GetFinalY(child);

                if (double.IsNaN(left) || double.IsNaN(top))
                {
                    var ec = child as EdgeControl;
                    if (!COUNT_ROUTE_PATHS || ec == null)
                    {
                        continue;
                    }
                    var routingInfo = ec.Edge as IRoutingInfo;
                    if (routingInfo == null)
                    {
                        continue;
                    }
                    var rps = routingInfo.RoutingPoints;
                    if (rps == null)
                    {
                        continue;
                    }
                    foreach (var item in rps)
                    {
                        //get the top left corner point
                        _topLeft.X = Math.Min(_topLeft.X, item.X);
                        _topLeft.Y = Math.Min(_topLeft.Y, item.Y);

                        //calculate the bottom right corner point
                        _bottomRight.X = Math.Max(_bottomRight.X, item.X);
                        _bottomRight.Y = Math.Max(_bottomRight.Y, item.Y);
                    }
                }
                else
                {
                    //get the top left corner point
                    _topLeft.X = Math.Min(_topLeft.X, left);
                    _topLeft.Y = Math.Min(_topLeft.Y, top);

                    //calculate the bottom right corner point
                    _bottomRight.X = Math.Max(_bottomRight.X, left + child.DesiredSize.Width);
                    _bottomRight.Y = Math.Max(_bottomRight.Y, top + child.DesiredSize.Height);
                }
            }
            var newSize = ContentSize;

            if (oldSize != newSize)
            {
                OnContentSizeChanged(oldSize, newSize);
            }
            return(DesignerProperties.GetIsInDesignMode(this) ? DesignSize : new Size(10, 10));
        }
示例#20
0
        private void UpdateVerticesLayout()
        {
            if (this.canvas == null ||
                this.Graph == null ||
                DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            var        builder = new WPFLayoutBuilder(this.canvas, this.elementsFactory);
            IDotRunner runner;

#if SILVERLIGHT
            runner = null;
#else
            if (string.IsNullOrWhiteSpace(this.DotExecutablePath) == false)
            {
                runner = new DotExeRunner {
                    DotExecutablePath = this.DotExecutablePath
                };
            }
            else
            {
                runner = new DotExeRunner();
            }
#endif

            if (this.LogGraphvizOutput)
            {
                runner = new DotRunnerLogDecorator(runner);
            }

            director = LayoutDirector.GetLayoutDirector(builder, dotRunner: runner);

            this.canvas.Children.Clear();
            this.progress = new ProgressBar {
                MinWidth = 100, MinHeight = 12, IsIndeterminate = true, Margin = new Thickness(50)
            };
            this.canvas.Children.Add(this.progress);
            try
            {
                director.StartBuilder(this.Graph);
#if SILVERLIGHT
                ThreadPool.QueueUserWorkItem(new LayoutAction(this, director).Run);
#else
                Task.Factory.StartNew(new LayoutAction(this, director).Run);
#endif
            }
            catch (Exception ex)
            {
                var textBlock = new TextBlock {
                    Width = 300, TextWrapping = TextWrapping.Wrap
                };
                textBlock.Text =
                    string.Format(
                        "Graphviz4Net: an exception was thrown during layouting." +
                        "Exception message: {0}.",
                        ex.Message);
                this.canvas.Children.Add(textBlock);
            }
        }
示例#21
0
 private static bool IsInDesignMode(DependencyObject element)
 {
     // Due to a known issue in Cider, GetIsInDesignMode attached property value is not enough to know if it's in design mode.
     return(DesignerProperties.GetIsInDesignMode(element) || Application.Current == null ||
            Application.Current.GetType() == typeof(Application));
 }
 public bool GetIsInDesignMode()
 {
     return(DesignerProperties.GetIsInDesignMode(this));
 }
示例#23
0
        public MapsListingViewModel()
        {
            DownloadMapFilesCommand = new DownloadMapFilesCommand(this);
            UpdateMapInfoCommand    = new UpdateMapInfoCommand(this);
            SendDynamicCmdCommand   = new SendDynamicCmdCommand();

            Maps = new ObservableCollection <Map>();
            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                Maps.Add(new Map()
                {
                    FullName          = "ze_licciana_pe",
                    CanDownload       = true,
                    AlreadyDownloaded = true,
                    DownloadableFiles = new List <MapFile>
                    {
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        }
                    }
                });

                Maps.Add(new Map()
                {
                    FullName          = "ze_fapescape_p5",
                    CanDownload       = false,
                    AlreadyDownloaded = true,
                    DownloadableFiles = new List <MapFile>
                    {
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        }
                    }
                });

                Maps.Add(new Map()
                {
                    FullName          = "ze_dust_pe",
                    CanDownload       = true,
                    AlreadyDownloaded = false,
                    DownloadableFiles = new List <MapFile>
                    {
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        },
                        new MapFile {
                            Name = "url1", Size = 535345
                        }
                    }
                });
            }
            else
            {
                var settings = new MapHandlerSettings
                {
                    FastdLinks    = Variables.Settings.FastdLinks.Select(x => x.Url).ToList(),
                    MapsDirectory = Variables.Settings.MapsDirectory
                };

                Mh = new MapHandler(settings);
                ReloadMaps();
            }
        }
示例#24
0
        private void UpdateIcon(bool forceDestroy = false)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            var  iconVisibility = IconVisibility;
            bool showIconInTray = !forceDestroy &&
                                  (iconVisibility == NotifyIconVisibility.Visible ||
                                   (iconVisibility == NotifyIconVisibility.UseControlVisibility && IsVisible));

            lock (_syncObj)
            {
                IntPtr iconHandle = IntPtr.Zero;

                try
                {
                    _allWindowsPermission.Demand();

                    if (showIconInTray && _hwndSource == null)
                    {
                        _hwndSource = new NotifyIconHwndSource(this);
                    }

                    if (_hwndSource != null)
                    {
                        _hwndSource.LockReference(showIconInTray);

                        var pnid = new NativeMethods.NOTIFYICONDATA
                        {
                            uCallbackMessage = (int)NativeMethods.WindowMessage.TrayMouseMessage,
                            uFlags           = NativeMethods.NotifyIconFlags.Message | NativeMethods.NotifyIconFlags.ToolTip,
                            hWnd             = _hwndSource.Handle,
                            uID   = _id,
                            szTip = Text
                        };
                        if (Icon != null)
                        {
                            iconHandle = NativeMethods.GetHIcon(Icon);

                            pnid.uFlags |= NativeMethods.NotifyIconFlags.Icon;
                            pnid.hIcon   = iconHandle;
                        }

                        if (showIconInTray && iconHandle != IntPtr.Zero)
                        {
                            if (!_iconCreated)
                            {
                                NativeMethods.Shell_NotifyIcon(0, pnid);
                                _iconCreated = true;
                            }
                            else
                            {
                                NativeMethods.Shell_NotifyIcon(1, pnid);
                            }
                        }
                        else if (_iconCreated)
                        {
                            NativeMethods.Shell_NotifyIcon(2, pnid);
                            _iconCreated = false;
                        }
                    }
                }
                finally
                {
                    if (iconHandle != IntPtr.Zero)
                    {
                        NativeMethods.DestroyIcon(iconHandle);
                    }
                }
            }
        }
示例#25
0
 public bool IsDesignMode()
 {
     return(DesignerProperties.GetIsInDesignMode(new DependencyObject()));
 }
示例#26
0
        /// <summary>
        /// Tries to find a suitable <see cref="ResourceManager"/> to use by default.
        /// </summary>
        /// <returns>
        /// A <see cref="ResourceManager"/> or <c>null</c> if suitable <see cref="ResourceManager"/>
        /// was not found.
        /// </returns>
        static ResourceManager GetDefaultResourceManager()
        {
            // The assembly in which to look for resources
            Assembly assembly;

            if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
            {
                // Design mode

                // Try to find the main assembly of the application

                var assemblies = AppDomain.CurrentDomain.GetAssemblies();

                assembly = null;

                // A .dll assembly
                Assembly libraryAssembly = null;

                foreach (var item in assemblies)
                {
                    if (item.GlobalAssemblyCache)
                    {
                        continue;
                    }

                    // The name of the assembly
                    var assemblyName = item.GetName().Name;

                    if (assemblyName.IndexOf("Microsoft", StringComparison.InvariantCultureIgnoreCase) >= 0 ||
                        assemblyName.IndexOf("Interop", StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        // Avoid Microsoft and interoperability assemblies loaded by Visual Studio

                        continue;
                    }

                    if (string.Equals(assemblyName, "Blend", StringComparison.InvariantCultureIgnoreCase))
                    {
                        // Avoid "Blend.exe" of the Expression Blend

                        continue;
                    }

                    var assemblyCompanyAttribute = (AssemblyCompanyAttribute)item.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false).FirstOrDefault();

                    if (assemblyCompanyAttribute != null && assemblyCompanyAttribute.Company.IndexOf("Microsoft", StringComparison.InvariantCultureIgnoreCase) >= 0)
                    {
                        // Avoid Microsoft assemblies loaded by Visual Studio

                        continue;
                    }

                    var resourceType = item.GetType(assemblyName + ".Properties.Resources", false);

                    if (resourceType != null)
                    {
                        // The assembly has default resources

                        if (item.EntryPoint != null)
                        {
                            // Check if the assembly contains WPF application (e.g. MyApplication.App class
                            // that derives from System.Windows.Application)

                            var applicationType = item.GetType(assemblyName + ".App", false);

                            if (applicationType != null && typeof(System.Windows.Application).IsAssignableFrom(applicationType))
                            {
                                // The assembly is valid

                                assembly = item;

                                break;
                            }
                        }
                        else
                        {
                            if (libraryAssembly == null)
                            {
                                libraryAssembly = item;
                            }
                        }
                    }
                }

                if (assembly == null)
                {
                    // The project must be a library project so use the first assembly that has
                    // default resources and does not belong to Microsoft

                    assembly = libraryAssembly;
                }
            }
            else
            {
                if (Application.Current != null && Application.Current.GetType() != typeof(Application))
                {
                    // The assembly of the current WPF application
                    assembly = Application.Current.GetType().Assembly;
                }
                else
                {
                    // The entry assembly of the application
                    assembly = Assembly.GetEntryAssembly();
                }
            }

            if (assembly != null)
            {
                try
                {
                    return(new ResourceManager(assembly.GetName().Name + ".Properties.Resources", assembly));
                }
                catch (MissingManifestResourceException)
                {
                    // The resoures cannot be found in the manifest of the assembly
                }
            }

            return(null);
        }
示例#27
0
        public TableControl()
        {
            InitializeComponent();
            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }
            var tableDef = Program.GameEngine.Definition.Table;
            var subbed   = SubscriptionModule.Get().IsSubscribed ?? false;

            if (subbed && !String.IsNullOrWhiteSpace(Prefs.DefaultGameBack) && File.Exists(Prefs.DefaultGameBack))
            {
                SetBackground(Prefs.DefaultGameBack, BackgroundStyle.UniformToFill);
            }
            else
            {
                if (tableDef.Background != null)
                {
                    SetBackground(tableDef);
                }
            }
            Program.GameEngine.BoardImage = Program.GameEngine.GameBoard.Source;
            //if (!Program.GameSettings.HideBoard)
            //    if (tableDef.Board != null)
            //        SetBoard(tableDef);

            if (!Program.GameSettings.UseTwoSidedTable)
            {
                middleLine.Visibility = Visibility.Collapsed;
            }

            if (Player.LocalPlayer.InvertedTable)
            {
                transforms.Children.Insert(0, new ScaleTransform(-1, -1));
            }

            _defaultWidth  = Program.GameEngine.Definition.DefaultSize().Width;
            _defaultHeight = Program.GameEngine.Definition.DefaultSize().Height;
            SizeChanged   += delegate
            {
                IsCardSizeValid = false;
                AspectRatioChanged();
            };
            MoveCards.Done  += CardMoved;
            CreateCard.Done += CardCreated;
            Unloaded        += delegate
            {
                MoveCards.Done  -= CardMoved;
                CreateCard.Done -= CardCreated;
            };
            Loaded += delegate { CenterView(); };
            //var didIt = false;
            //Loaded += delegate
            //{
            //if (didIt) return;
            //didIt = true;
            //foreach (var p in Player.AllExceptGlobal.GroupBy(x => x.InvertedTable))
            //{
            //    var sx = Program.GameEngine.BoardMargin.Left;
            //    var sy = Program.GameEngine.BoardMargin.Bottom;
            //    if (p.Key == true)
            //    {
            //        sy = Program.GameEngine.BoardMargin.Top;
            //        sx = Program.GameEngine.BoardMargin.Right;
            //    }
            //    foreach (var player in p)
            //    {
            //        foreach (var tgroup in player.TableGroups)
            //        {
            //            var pile = new AdhocPileControl();
            //            pile.DataContext = tgroup;
            //            PlayerCanvas.Children.Add(pile);
            //            Canvas.SetLeft(pile, sx);
            //            Canvas.SetTop(pile, sy);
            //            if (p.Key)
            //                sx -= Program.GameEngine.Definition.CardWidth * 2;
            //            else
            //                sx += Program.GameEngine.Definition.CardWidth * 2;
            //        }
            //        if (p.Key)
            //            sx -= Program.GameEngine.Definition.CardWidth * 4;
            //        else
            //            sx += Program.GameEngine.Definition.CardWidth * 4;
            //    }
            //}
            //};
            Program.GameEngine.PropertyChanged += GameOnPropertyChanged;
            if (Player.LocalPlayer.InvertedTable)
            {
                var rotateAnimation = new DoubleAnimation(0, 180, TimeSpan.FromMilliseconds(1));
                var rt = (RotateTransform)NoteCanvas.RenderTransform;
                rt.BeginAnimation(RotateTransform.AngleProperty, rotateAnimation);
            }

            Player.LocalPlayer.PropertyChanged += LocalPlayerOnPropertyChanged;
        }
示例#28
0
        private void OnRender()
        {
            if (Plotter == null)
            {
                return;
            }

            if (DesignerProperties.GetIsInDesignMode(this))
            {
                return;
            }

            if (rendering && !renderingPending)
            {
                Dispatcher.BeginInvoke(OnRender);
                return;
            }

            if (rendering)
            {
                return;
            }

            rendering        = true;
            renderingPending = false;

            ContentPanel.Children.Clear();

            var  transform = Plotter.Viewport.Transform;
            Rect output    = Plotter.Viewport.Output;

            DataRect visible   = Plotter.Viewport.Visible;
            var      tileInfos = GetVisibleTiles();

            var lowerTiles = GetLoadedLowerTiles(tileInfos);

            foreach (var tile in lowerTiles)
            {
                var id = tile.Id;
                if (TileSystem.IsLoaded(id))
                {
                    var      bmp         = TileSystem[id];
                    DataRect visibleRect = Transform(TileProvider.GetTileBounds(id));
                    Rect     screenRect  = visibleRect.DataToScreen(transform);

                    DrawTile(bmp, screenRect, visibleRect, tile.Clip);
                }
                else
                {
                    TileSystem.BeginLoadImage(id);
                }
            }

            foreach (var tileInfo in tileInfos)
            {
                if (TileSystem.IsLoaded(tileInfo.Tile))
                {
                    var bmp = TileSystem[tileInfo.Tile];
                    DrawTile(bmp, tileInfo.ScreenBounds, tileInfo.VisibleBounds, null);
                }
                else
                {
                    TileSystem.BeginLoadImage(tileInfo.Tile);
                }
            }

            rendering = false;
        }
示例#29
0
 static View()
 {
     _isDesignMode = DesignerProperties.GetIsInDesignMode(new ContentControl());
 }
        /// <summary>
        /// Converts the SVG source file to <see cref="Uri"/>
        /// </summary>
        /// <param name="inputParameter">
        /// Object that can provide services for the markup extension.
        /// </param>
        /// <returns>
        /// Returns the valid <see cref="Uri"/> of the SVG source path if
        /// successful; otherwise, it returns <see langword="null"/>.
        /// </returns>
        private Uri ResolveUri(string inputParameter)
        {
            if (string.IsNullOrWhiteSpace(inputParameter))
            {
                return(null);
            }

            Uri svgSource;

            if (Uri.TryCreate(inputParameter, UriKind.RelativeOrAbsolute, out svgSource))
            {
                if (svgSource.IsAbsoluteUri)
                {
                    return(svgSource);
                }
                // Try getting a local file in the same directory....
                string svgPath = inputParameter;
                if (inputParameter[0] == '\\' || inputParameter[0] == '/')
                {
                    svgPath = inputParameter.Substring(1);
                }
                svgPath = svgPath.Replace('/', '\\');

                Assembly assembly  = Assembly.GetExecutingAssembly();
                string   localFile = Path.Combine(Path.GetDirectoryName(
                                                      assembly.Location), svgPath);

                if (File.Exists(localFile))
                {
                    return(new Uri(localFile));
                }

                // Try getting it as resource file...
                var inputUri = _uriConverter.ConvertFrom(inputParameter) as Uri;
                if (inputUri != null)
                {
                    return(inputUri.IsAbsoluteUri ? inputUri : new Uri(_baseUri, inputUri));
                }
                string asmName = assembly.GetName().Name;

                svgPath = inputParameter;
                if (inputParameter.StartsWith("/", StringComparison.OrdinalIgnoreCase))
                {
                    svgPath = svgPath.TrimStart('/');
                }

                // A little hack to display preview in design mode
                bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject());
                if (designTime && !string.IsNullOrWhiteSpace(_appName))
                {
                    string uriDesign = string.Format("/{0};component/{1}", _appName, svgPath);

                    return(new Uri(uriDesign, UriKind.Relative));
                }

                string uriString = string.Format("pack://application:,,,/{0};component/{1}",
                                                 asmName, svgPath);

                return(new Uri(uriString));
            }

            return(null);
        }