public static bool IsInDesignMode(this DependencyObject source) { return(DesignerProperties.GetIsInDesignMode(source)); }
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)); } }
public SKElement() { designMode = DesignerProperties.GetIsInDesignMode(this); }
public GameElement(IGame game) { _designMode = DesignerProperties.GetIsInDesignMode(this); _game = game; CompositionTarget.Rendering += CompositionTargetRendering; }
/// <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)); }
/// <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); }
private void initialise() { if (DesignerProperties.GetIsInDesignMode(this)) { return; } if (this.textbox != null) { throw new Exception("Auto completion popup cannot be initialised more than once."); } this.textbox = this.TextBox; if (this.textbox == null) { throw new Exception("Auto completion popup must have a valid text box."); } this.textbox.PreviewKeyDown += this.textboxOnPreviewKeyDown; this.textbox.TextChanged += this.textboxOnTextChanged; this.textbox.LostKeyboardFocus += (sender, args) => { if (this.textbox.Focusable && this.textbox.IsEnabled) { var isKeyboardFocusWithin = popup.IsKeyboardFocusWithin; if (isKeyboardFocusWithin) { if (listBox.IsKeyboardFocusWithin) { this.textbox.Focus(); } return; } } this.close(); }; this.popup.LostKeyboardFocus += (sender, args) => { if (!this.textbox.IsKeyboardFocusWithin && !this.popup.IsKeyboardFocusWithin) { this.close(); } }; this.popup.PreviewKeyDown += (sender, args) => { if (args.Key == Key.Tab) { if (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)) { this.textbox.Focus(); args.Handled = true; } else { if (this.textbox.PredictFocus(FocusNavigationDirection.Down) is UIElement nextElement) { Keyboard.Focus(nextElement); args.Handled = true; } } } else if (args.Key == Key.Down || args.Key == Key.Up || args.Key == Key.Escape) { this.textbox.Focus(); args.Handled = true; } }; }
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { if (DesignerProperties.GetIsInDesignMode(new DependencyObject())) { return(Visibility.Visible); }
/// <summary> /// This method is invoked when the value bound at the dependency /// property SelectedItem has changed. /// </summary> /// <param name="d"></param> /// <param name="e"></param> private static void OnSelectedItemChanged(DependencyObject d , DependencyPropertyChangedEventArgs e) { try { // do not implement interaction logic for WPF Design-Time if (DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())) { return; } var tree = d as TreeView; // Sanity check: Are we looking at the least required data we need? var itemNode = e.NewValue as IParent; if (itemNode == null) // Filter out Desktop { return; } Stack <object> Nodes = new Stack <object>(); // Unwind IParent Stack for (; itemNode != null; itemNode = itemNode.GetParent()) { if (itemNode.GetParent() != null) { Nodes.Push(itemNode); } } var newNode = Nodes.ToArray(); if (newNode.Length <= 1) // Traverse path in a forward fashion { return; } // params look good so lets find the attached tree view (aka ItemsControl) //var behavior = d as BringVirtualTreeViewItemIntoViewBehavior; //var tree = behavior.AssociatedObject; var currentParent = tree as ItemsControl; // Now loop through each item in the array of bound path items and make sure they exist for (int i = 0; i < newNode.Length; i++) { var node = newNode[i]; // first try the easy way var newParent = currentParent.ItemContainerGenerator.ContainerFromItem(node) as TreeViewItem; if (newParent == null) { try { // if this failed, it's probably because of virtualization, and we will have to do it the hard way. // this code is influenced by TreeViewItem.ExpandRecursive decompiled code, and the MSDN sample at // http://code.msdn.microsoft.com/Changing-selection-in-a-6a6242c8/sourcecode?fileId=18862&pathId=753647475 // see also the question at http://stackoverflow.com/q/183636/46635 currentParent.ApplyTemplate(); var itemsPresenter = (ItemsPresenter)currentParent.Template.FindName("ItemsHost", currentParent); if (itemsPresenter != null) { itemsPresenter.ApplyTemplate(); } else { currentParent.UpdateLayout(); } var virtualizingPanel = GetItemsHost(currentParent) as VirtualizingPanel; CallEnsureGenerator(virtualizingPanel); var index = currentParent.Items.IndexOf(node); if (index < 0) { // This is raised when the item in the path array is not part of the tree collection // This can be tricky, because Binding an ObservableDictionary to the treeview will // require that we need an array of KeyValuePairs<K,T>[] here :-( #if DEBUG System.Console.WriteLine("Node '" + node + "' cannot be fount in container"); //// throw new InvalidOperationException("Node '" + node + "' cannot be fount in container"); #else // Use your favourite logger here since the exception will otherwise kill the appliaction System.Console.WriteLine("Node '" + node + "' cannot be fount in container"); #endif return; } virtualizingPanel.BringIndexIntoViewPublic(index); newParent = currentParent.ItemContainerGenerator.ContainerFromIndex(index) as TreeViewItem; } catch { return; } } if (newParent == null) { #if DEBUG System.Console.WriteLine("Node '" + node + "' cannot be fount in container"); //// throw new InvalidOperationException("Tree view item cannot be found or created for node '" + node + "'"); #else // Use your favourite logger here since the exception will otherwise kill the appliaction System.Console.WriteLine("Node '" + node + "' cannot be fount in container"); #endif } if (node == newNode[newNode.Length - 1]) { newParent.IsSelected = true; newParent.BringIntoView(); break; } // Make sure nodes (except for last child node) are expanded to make children visible if (i < newNode.Length - 1) { newParent.IsExpanded = true; } currentParent = newParent; } } catch (Exception exp) { System.Console.WriteLine("Exception in TreeViewVirtualItemBehaviour.OnSelectedItemChanged:"); System.Console.WriteLine(exp.Message); System.Console.WriteLine(exp.StackTrace); } }
protected void SetFromColor(Color color) { if ((DesignerProperties.GetIsInDesignMode(this)) || (!IsMeasureValid)) { return; } /* * In this control, base colors are such colors where one component is set to 0 * and another to 255 (third one can be anything from 0 to 255). This construct * is useful because these are the colors represented on the xamlBaseColors scale. * * This function uses an assumption that highest component of inputed color * corresponds with the highest one of base color (255) and the lowest one with 0. * * Therefore, we must must sort indexes of colors in ascending order. * We need to know which value in bytes is the highest and which the lowest, * without disrupting the order of bytes (which we'll need later). * After this code, bytes[indexes[0]] will be the lowest byte and bytes[indexes[2]] the highest. */ byte[] bytes = new byte[] { color.R, color.G, color.B }; byte[] indexes = new byte[] { 0, 1, 2 }; for (int i = 0; i < 2; i++) { for (int j = i + 1; j < 3; j++) { if (bytes[indexes[i]] > bytes[indexes[j]]) { byte temp = indexes[i]; indexes[i] = indexes[j]; indexes[j] = temp; } } } /* * Now we can find base color of the inputed color, as well as x and y, * which are distances of the picked color from the base color * (in the upper right corner of the detail picker). * * Note that in this case, y is oriented from DOWN UP (y == 0 is at the bottom of control). * This is opposite of normal screen coordinates, but matches the logic that x & y are * parameters applied to the base color. Therefore, x,y == [1,1] would be the base color, * lower x's add whiteness and lower y's darkness. [0,1] is white, and [1,0] and [0,0] are black. */ double x; if ((double)bytes[indexes[0]] == 0) { x = 1; } else { x = 1D - (double)bytes[indexes[0]] / (double)bytes[indexes[2]]; } double y = (double)bytes[indexes[2]] / 255D; bytes[indexes[0]] = 0; bytes[indexes[1]] = (byte)(((double)bytes[indexes[1]] - 255D * y * (1D - x)) / (x * y)); bytes[indexes[2]] = 255; Color baseColor = Color.FromRgb(bytes[0], bytes[1], bytes[2]); /* * Now that we have baseColor, we need to find its position on xamlBaseColors, * so we could position the selector. */ double pickedY = 0; double ratioStep = 1D / ((double)_baseColors.Length - 1D); for (int i = 0; i < _baseColors.Length - 1; i++) { if (((_baseColors[i].R & _baseColors[i + 1].R) <= baseColor.R) && ((_baseColors[i].R | _baseColors[i + 1].R) >= baseColor.R) && ((_baseColors[i].G & _baseColors[i + 1].G) <= baseColor.G) && ((_baseColors[i].G | _baseColors[i + 1].G) >= baseColor.G) && ((_baseColors[i].B & _baseColors[i + 1].B) <= baseColor.B) && ((_baseColors[i].B | _baseColors[i + 1].B) >= baseColor.B)) { double localDiff = Math.Abs(_baseColors[i].R - baseColor.R) + Math.Abs(_baseColors[i].G - baseColor.G) + Math.Abs(_baseColors[i].B - baseColor.B); double localRatio = (localDiff * ratioStep) / 255D; double totalRatio = localRatio + ratioStep * i; pickedY = totalRatio * xamlBaseColors.ActualHeight; break; } } // *NEW* // Find position on alpha picker scale according to color's alpha value double pickedAlphaY = xamlAlphaScale.ActualHeight - ((double)color.A * xamlAlphaScale.ActualHeight) / 255d; // Apply the findings. // There's a little bit of overhead here, but IMO this is logically the soundest approach. PickedBaseValue = pickedY; PickedAlphaValue = pickedAlphaY; PickedDetailPoint = new Point( x * xamlDetailColor.ActualWidth, (1 - y) * xamlDetailColor.ActualHeight); }
/// <summary> /// Checks if is in design mode. /// </summary> /// <param name="element">The element</param> /// <returns>True if in design mode</returns> public static bool IsInDesignMode(DependencyObject element) { return(DesignerProperties.GetIsInDesignMode(element)); }
public MainPresenter() { DesignMode = DesignerProperties.GetIsInDesignMode(this); _closeTimer.Tick += new EventHandler(CloseTimer_Tick); _closeTimer.Interval = new TimeSpan(1000); if (!DesignMode) { _closeTimer.Start(); } var presenter = (IPresenter)Shell.Instance; LoadRoleListCache(); presenter.OnShowError += (message, title) => { Shell.Instance.ShowView( typeof(Views.ErrorDisplay).AssemblyQualifiedName, "errorViewSource", new ViewModels.Error { ErrorContent = message }, "Error"); }; presenter.OnShowStatus += (status) => { Shell.Instance.ShowView( typeof(Views.StatusDisplay).AssemblyQualifiedName, "statusViewSource", status, "Status"); }; presenter.OnShowView += (view, region) => { switch (region) { case "Main": MainContent = view.ViewInstance; break; case "Menu": MenuContent = view.ViewInstance; break; case "User": UserContent = view.ViewInstance; break; case "Error": _errorClose = DateTime.Now.Add(new TimeSpan(0, 0, 5)); ErrorContent = view.ViewInstance; break; case "Status": _statusClose = DateTime.Now.Add(new TimeSpan(0, 0, 5)); if (view.Model != null) { AppBusy = ((Status)view.Model).IsBusy; } else { AppBusy = false; } StatusContent = view.ViewInstance; break; default: break; } }; Shell.Instance.ShowView( typeof(Views.UserDisplay).AssemblyQualifiedName, "userViewSource", new ViewModels.User(), "User"); Shell.Instance.ShowView( typeof(Views.Dashboard).AssemblyQualifiedName, "dashboardViewSource", new ViewModels.Dashboard(), "Main"); ShowMenu(); Shell.Instance.ShowStatus(new Status { Text = "Ready" }); }
public WpfHost(global::System.Windows.Threading.Dispatcher dispatcher, Func <WinUI.Application> appBuilder, string[] args = null) { _current = this; args ??= Environment .GetCommandLineArgs() .Skip(1) .ToArray(); designMode = DesignerProperties.GetIsInDesignMode(this); void CreateApp(WinUI.ApplicationInitializationCallbackParams _) { var app = appBuilder(); app.Host = this; } bool EnqueueNative(DispatcherQueuePriority priority, DispatcherQueueHandler callback) { if (priority == DispatcherQueuePriority.Normal) { dispatcher.BeginInvoke(callback); } else { var p = priority switch { DispatcherQueuePriority.Low => DispatcherPriority.Background, DispatcherQueuePriority.High => DispatcherPriority.Send, // This one is higher than normal _ => DispatcherPriority.Normal }; dispatcher.BeginInvoke(p, callback); } return(true); } Windows.System.DispatcherQueue.EnqueueNativeOverride = EnqueueNative; Windows.UI.Core.CoreDispatcher.DispatchOverride = d => dispatcher.BeginInvoke(d); Windows.UI.Core.CoreDispatcher.HasThreadAccessOverride = dispatcher.CheckAccess; WinUI.Application.Start(CreateApp, args); WinUI.Window.InvalidateRender += () => { InvalidateFocusVisual(); InvalidateVisual(); }; WpfApplication.Current.Activated += Current_Activated; WpfApplication.Current.Deactivated += Current_Deactivated; WpfApplication.Current.MainWindow.StateChanged += MainWindow_StateChanged; Windows.Foundation.Size preferredWindowSize = ApplicationView.PreferredLaunchViewSize; if (preferredWindowSize != Windows.Foundation.Size.Empty) { WpfApplication.Current.MainWindow.Width = (int)preferredWindowSize.Width; WpfApplication.Current.MainWindow.Height = (int)preferredWindowSize.Height; } SizeChanged += WpfHost_SizeChanged; Loaded += WpfHost_Loaded; }
// connect to an NDI source in our Dictionary by name private void Connect(Source source) { if (DesignerProperties.GetIsInDesignMode(this)) { return; } // before we are connected, we need to set up our image // it's bad practice to do this in the constructor if (Child == null) { Child = VideoSurface; } // just to be safe Disconnect(); // Sanity if (source == null || String.IsNullOrEmpty(source.Name)) { return; } if (String.IsNullOrEmpty(ReceiverName)) { throw new ArgumentException("ReceiverName can not be null or empty.", ReceiverName); } // a source_t to describe the source to connect to. NDIlib.source_t source_t = new NDIlib.source_t() { p_ndi_name = UTF.StringToUtf8(source.Name) }; // make a description of the receiver we want NDIlib.recv_create_v3_t recvDescription = new NDIlib.recv_create_v3_t() { // the source we selected source_to_connect_to = source_t, // we want BGRA frames for this example color_format = NDIlib.recv_color_format_e.recv_color_format_BGRX_BGRA, // we want full quality - for small previews or limited bandwidth, choose lowest bandwidth = NDIlib.recv_bandwidth_e.recv_bandwidth_highest, // let NDIlib deinterlace for us if needed allow_video_fields = false, // The name of the NDI receiver to create. This is a NULL terminated UTF8 string and should be // the name of receive channel that you have. This is in many ways symettric with the name of // senders, so this might be "Channel 1" on your system. p_ndi_recv_name = UTF.StringToUtf8(ReceiverName) }; // create a new instance connected to this source _recvInstancePtr = NDIlib.recv_create_v3(ref recvDescription); // free the memory we allocated with StringToUtf8 Marshal.FreeHGlobal(source_t.p_ndi_name); Marshal.FreeHGlobal(recvDescription.p_ndi_recv_name); // did it work? System.Diagnostics.Debug.Assert(_recvInstancePtr != IntPtr.Zero, "Failed to create NDI receive instance."); if (_recvInstancePtr != IntPtr.Zero) { // We are now going to mark this source as being on program output for tally purposes (but not on preview) SetTallyIndicators(true, false); // start up a thread to receive on _exitThread = false; _receiveThread = new Thread(ReceiveThreadProc) { IsBackground = true, Name = "NdiExampleReceiveThread" }; _receiveThread.Start(); _videoEnabled = true; } }
private static void InitAnimationOrImage(Image?imageControl) { if (imageControl == null) { return; } var 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; } ObjectAnimationUsingKeyFrames?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; } RepeatBehavior repeatBehavior = GetRepeatBehavior(imageControl); bool synchronized = GetSynchronizedBySource(imageControl); AnimationCache.IncrementReferenceCount(source, repeatBehavior); AnimationClock?clock; if (synchronized) { clock = AnimationCache.GetClock(source, repeatBehavior); if (clock == null) { clock = animation.CreateClock(); AnimationCache.AddClock(source, repeatBehavior, clock); } } else { clock = animation.CreateClock(); } var controller = new ImageAnimationController(imageControl, animation, clock); SetAnimationController(imageControl, controller); SetIsAnimationLoaded(imageControl, true); imageControl.RaiseEvent(new RoutedEventArgs(AnimationLoadedEvent, imageControl)); return; } } imageControl.Source = source; }
public static bool IsDesignTime(this Application application) { return(DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual)); }
/// <summary> /// This converts the SVG resource specified by the Uri to <see cref="DrawingGroup"/>. /// </summary> /// <param name="svgSource">A <see cref="Uri"/> specifying the source of the SVG resource.</param> /// <returns>A <see cref="DrawingGroup"/> of the converted SVG resource.</returns> protected virtual DrawingGroup GetDrawing(Uri svgSource) { string scheme = null; // A little hack to display preview in design mode: The design mode Uri is not absolute. bool designTime = DesignerProperties.GetIsInDesignMode(new DependencyObject()); if (designTime && svgSource.IsAbsoluteUri == false) { scheme = "pack"; } else { scheme = svgSource.Scheme; } if (string.IsNullOrWhiteSpace(scheme)) { return(null); } WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = _includeRuntime; settings.TextAsGeometry = _textAsGeometry; settings.OptimizePath = _optimizePath; if (_culture != null) { settings.CultureInfo = _culture; } switch (scheme) { case "file": //case "ftp": case "https": case "http": using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(svgSource); if (drawGroup != null) { return(drawGroup); } } break; case "pack": StreamResourceInfo svgStreamInfo = null; if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0) { svgStreamInfo = Application.GetRemoteStream(svgSource); } else { svgStreamInfo = Application.GetResourceStream(svgSource); } Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null; if (svgStream != null) { string fileExt = Path.GetExtension(svgSource.ToString()); bool isCompressed = !string.IsNullOrWhiteSpace(fileExt) && string.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase); if (isCompressed) { using (svgStream) { using (var zipStream = new GZipStream(svgStream, CompressionMode.Decompress)) { using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(zipStream); if (drawGroup != null) { return(drawGroup); } } } } } else { using (svgStream) { using (FileSvgReader reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(svgStream); if (drawGroup != null) { return(drawGroup); } } } } } break; case "data": var sourceData = svgSource.OriginalString.Replace(" ", ""); int nColon = sourceData.IndexOf(":", StringComparison.OrdinalIgnoreCase); int nSemiColon = sourceData.IndexOf(";", StringComparison.OrdinalIgnoreCase); int nComma = sourceData.IndexOf(",", StringComparison.OrdinalIgnoreCase); string sMimeType = sourceData.Substring(nColon + 1, nSemiColon - nColon - 1); string sEncoding = sourceData.Substring(nSemiColon + 1, nComma - nSemiColon - 1); if (string.Equals(sMimeType.Trim(), "image/svg+xml", StringComparison.OrdinalIgnoreCase) && string.Equals(sEncoding.Trim(), "base64", StringComparison.OrdinalIgnoreCase)) { string sContent = SvgObject.RemoveWhitespace(sourceData.Substring(nComma + 1)); byte[] imageBytes = Convert.FromBase64CharArray(sContent.ToCharArray(), 0, sContent.Length); bool isGZiped = sContent.StartsWith(SvgObject.GZipSignature, StringComparison.Ordinal); if (isGZiped) { using (var stream = new MemoryStream(imageBytes)) { using (GZipStream zipStream = new GZipStream(stream, CompressionMode.Decompress)) { using (var reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(zipStream); if (drawGroup != null) { return(drawGroup); } } } } } else { using (var stream = new MemoryStream(imageBytes)) { using (var reader = new FileSvgReader(settings)) { DrawingGroup drawGroup = reader.Read(stream); if (drawGroup != null) { return(drawGroup); } } } } } break; } return(null); }
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); } } } }
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, "uniformToFill"); } else { if (tableDef.Background != null) { SetBackground(tableDef); } } Program.GameEngine.BoardImage = tableDef.Board; //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.CardWidth; _defaultHeight = Program.GameEngine.Definition.CardHeight; SizeChanged += delegate { IsCardSizeValid = false; AspectRatioChanged(); }; MoveCard.Done += CardMoved; CreateCard.Done += CardCreated; Unloaded += delegate { MoveCard.Done -= CardMoved; CreateCard.Done -= CardCreated; }; Loaded += delegate { CenterView(); }; 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); } //this.IsManipulationEnabled = true; //this.ManipulationDelta += OnManipulationDelta; Player.LocalPlayer.PropertyChanged += LocalPlayerOnPropertyChanged; }
public override void OnApplyTemplate() { base.OnApplyTemplate(); ButtonPlayAction = Template.FindName("PART_ButtonPlayAction", this) as Button; if (ButtonPlayAction != null) { BindingTools.SetBinding(ButtonPlayAction, Button.CommandProperty, nameof(GameDetailsViewModel.PlayCommand)); BindingTools.SetBinding(ButtonPlayAction, Button.ContentProperty, nameof(GameDetailsViewModel.ContextActionDescription)); BindingTools.SetBinding(ButtonPlayAction, Button.VisibilityProperty, nameof(GameDetailsViewModel.IsPlayAvailable), converter: new BooleanToVisibilityConverter()); } ButtonContextAction = Template.FindName("PART_ButtonContextAction", this) as Button; if (ButtonContextAction != null) { BindingTools.SetBinding(ButtonContextAction, Button.CommandProperty, nameof(GameDetailsViewModel.ContextActionCommand)); BindingTools.SetBinding(ButtonContextAction, Button.ContentProperty, nameof(GameDetailsViewModel.ContextActionDescription)); BindingTools.SetBinding(ButtonContextAction, Button.VisibilityProperty, nameof(GameDetailsViewModel.IsContextAvailable), converter: new BooleanToVisibilityConverter()); } ButtonMoreActions = Template.FindName("PART_ButtonMoreActions", this) as Button; if (ButtonMoreActions != null) { LeftClickContextMenuBehavior.SetEnabled(ButtonMoreActions, true); if (!DesignerProperties.GetIsInDesignMode(this)) { ButtonMoreActions.ContextMenu = new GameMenu(mainModel) { ShowStartSection = false, Placement = PlacementMode.Bottom }; BindingTools.SetBinding(ButtonMoreActions.ContextMenu, Button.DataContextProperty, mainModel, nameof(DesktopAppViewModel.SelectedGame)); } } ButtonEditGame = Template.FindName("PART_ButtonEditGame", this) as Button; if (ButtonEditGame != null) { BindingTools.SetBinding(ButtonEditGame, Button.CommandProperty, nameof(GameDetailsViewModel.EditGameCommand)); } HtmlDescription = Template.FindName("PART_HtmlDescription", this) as HtmlTextView; if (HtmlDescription != null) { BindingTools.SetBinding(HtmlDescription, HtmlTextView.HtmlTextProperty, GetGameBindingPath(nameof(GamesCollectionViewEntry.Description))); BindingTools.SetBinding(HtmlDescription, HtmlTextView.VisibilityProperty, nameof(GameDetailsViewModel.DescriptionVisibility)); } ImageCover = Template.FindName("PART_ImageCover", this) as Image; if (ImageCover != null) { BindingTools.SetBinding(ImageCover, Image.SourceProperty, GetGameBindingPath(nameof(GamesCollectionViewEntry.CoverImageObject)), converter: new NullToDependencyPropertyUnsetConverter(), mode: BindingMode.OneWay); BindingTools.SetBinding(ImageCover, Image.VisibilityProperty, nameof(GameDetailsViewModel.CoverVisibility), mode: BindingMode.OneWay); } ImageIcon = Template.FindName("PART_ImageIcon", this) as Image; if (ImageIcon != null) { var sourceBinding = new PriorityBinding(); sourceBinding.Bindings.Add(new Binding() { Path = new PropertyPath(GetGameBindingPath(nameof(GamesCollectionViewEntry.IconObject))), Converter = new NullToDependencyPropertyUnsetConverter(), Mode = BindingMode.OneWay }); sourceBinding.Bindings.Add(new Binding() { Path = new PropertyPath(GetGameBindingPath(nameof(GamesCollectionViewEntry.DefaultIconObject))), Converter = new NullToDependencyPropertyUnsetConverter(), Mode = BindingMode.OneWay }); BindingOperations.SetBinding(ImageIcon, Image.SourceProperty, sourceBinding); BindingTools.SetBinding(ImageIcon, Image.VisibilityProperty, nameof(GameDetailsViewModel.IconVisibility), mode: BindingMode.OneWay); } ImageBackground = Template.FindName("PART_ImageBackground", this) as FadeImage; if (ImageBackground != null) { SetBackgroundBinding(); BindingTools.SetBinding(ImageBackground, Image.VisibilityProperty, nameof(GameDetailsViewModel.BackgroundVisibility), mode: BindingMode.OneWay); BindingTools.SetBinding(ImageBackground, FadeImage.AnimationEnabledProperty, mainModel.AppSettings, nameof(PlayniteSettings.BackgroundImageAnimation), mode: BindingMode.OneWay); } SetElemVisibility(ref ElemPlayTime, "PART_ElemPlayTime", nameof(GameDetailsViewModel.PlayTimeVisibility)); SetElemVisibility(ref ElemLastPlayed, "PART_ElemLastPlayed", nameof(GameDetailsViewModel.LastPlayedVisibility)); SetElemVisibility(ref ElemCompletionStatus, "PART_ElemCompletionStatus", nameof(GameDetailsViewModel.CompletionStatusVisibility)); SetElemVisibility(ref ElemLibrary, "PART_ElemLibrary", nameof(GameDetailsViewModel.SourceLibraryVisibility)); SetElemVisibility(ref ElemPlatform, "PART_ElemPlatform", nameof(GameDetailsViewModel.PlatformVisibility)); SetElemVisibility(ref ElemGenres, "PART_ElemGenres", nameof(GameDetailsViewModel.GenreVisibility)); SetElemVisibility(ref ElemDevelopers, "PART_ElemDevelopers", nameof(GameDetailsViewModel.DeveloperVisibility)); SetElemVisibility(ref ElemPublishers, "PART_ElemPublishers", nameof(GameDetailsViewModel.PublisherVisibility)); SetElemVisibility(ref ElemReleaseDate, "PART_ElemReleaseDate", nameof(GameDetailsViewModel.ReleaseDateVisibility)); SetElemVisibility(ref ElemTags, "PART_ElemTags", nameof(GameDetailsViewModel.TagVisibility)); SetElemVisibility(ref ElemFeatures, "PART_ElemFeatures", nameof(GameDetailsViewModel.FeatureVisibility)); SetElemVisibility(ref ElemCategories, "PART_ElemCategories", nameof(GameDetailsViewModel.CategoryVisibility)); SetElemVisibility(ref ElemLinks, "PART_ElemLinks", nameof(GameDetailsViewModel.LinkVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemDescription", nameof(GameDetailsViewModel.DescriptionVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemAgeRating", nameof(GameDetailsViewModel.AgeRatingVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemSeries", nameof(GameDetailsViewModel.SeriesVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemRegion", nameof(GameDetailsViewModel.RegionVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemSource", nameof(GameDetailsViewModel.SourceVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemVersion", nameof(GameDetailsViewModel.VersionVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemCommunityScore", nameof(GameDetailsViewModel.CommunityScoreVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemCriticScore", nameof(GameDetailsViewModel.CriticScoreVisibility)); SetElemVisibility(ref ElemDescription, "PART_ElemUserScore", nameof(GameDetailsViewModel.UserScoreVisibility)); SetGameItemButtonBinding(ref ButtonLibrary, "PART_ButtonLibrary", nameof(GameDetailsViewModel.SetLibraryFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.PluginId)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.LibraryPlugin)}.{nameof(GamesCollectionViewEntry.LibraryPlugin.Name)}"), nameof(GameDetailsViewModel.SourceLibraryVisibility)); SetGameItemButtonBinding(ref ButtonPlatform, "PART_ButtonPlatform", nameof(GameDetailsViewModel.SetPlatformFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.Platform)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.Platform)}.{nameof(GamesCollectionViewEntry.Platform.Name)}"), nameof(GameDetailsViewModel.PlatformVisibility)); SetGameItemButtonBinding(ref ButtonReleaseDate, "PART_ButtonReleaseDate", nameof(GameDetailsViewModel.SetReleaseDateFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.ReleaseDate)), GetGameBindingPath(nameof(GamesCollectionViewEntry.ReleaseDate)), nameof(GameDetailsViewModel.ReleaseDateVisibility), new NullableDateToStringConverter()); SetGameItemButtonBinding(ref ButtonVersion, "PART_ButtonVersion", nameof(GameDetailsViewModel.SetVersionFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.Version)), GetGameBindingPath(nameof(GamesCollectionViewEntry.Version)), nameof(GameDetailsViewModel.VersionVisibility)); SetGameItemButtonBinding(ref ButtonAgeRating, "PART_ButtonAgeRating", nameof(GameDetailsViewModel.SetAgeRatingCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.AgeRating)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.AgeRating)}.{nameof(GamesCollectionViewEntry.AgeRating.Name)}"), nameof(GameDetailsViewModel.AgeRatingVisibility)); SetGameItemButtonBinding(ref ButtonSeries, "PART_ButtonSeries", nameof(GameDetailsViewModel.SetSeriesFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.Series)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.Series)}.{nameof(GamesCollectionViewEntry.Series.Name)}"), nameof(GameDetailsViewModel.SeriesVisibility)); SetGameItemButtonBinding(ref ButtonSource, "PART_ButtonSource", nameof(GameDetailsViewModel.SetSourceFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.Source)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.Source)}.{nameof(GamesCollectionViewEntry.Source.Name)}"), nameof(GameDetailsViewModel.SourceVisibility)); SetGameItemButtonBinding(ref ButtonRegion, "PART_ButtonRegion", nameof(GameDetailsViewModel.SetRegionFilterCommand), GetGameBindingPath(nameof(GamesCollectionViewEntry.Region)), GetGameBindingPath($"{nameof(GamesCollectionViewEntry.Region)}.{nameof(GamesCollectionViewEntry.Region.Name)}"), nameof(GameDetailsViewModel.RegionVisibility)); SetGameItemTextBinding(ref TextPlayTime, "PART_TextPlayTime", nameof(GameDetailsViewModel.Game.Playtime), nameof(GameDetailsViewModel.PlayTimeVisibility), new LongToTimePlayedConverter()); SetGameItemTextBinding(ref TextLastActivity, "PART_TextLastActivity", nameof(GameDetailsViewModel.Game.LastActivity), nameof(GameDetailsViewModel.LastPlayedVisibility), new DateTimeToLastPlayedConverter()); SetGameItemTextBinding(ref TextCompletionStatus, "PART_TextCompletionStatus", nameof(GameDetailsViewModel.Game.CompletionStatus), nameof(GameDetailsViewModel.CompletionStatusVisibility), new ObjectToStringConverter()); SetGameItemTextBinding(ref TextCommunityScore, "PART_TextCommunityScore", nameof(GameDetailsViewModel.Game.CommunityScore), nameof(GameDetailsViewModel.CommunityScoreVisibility)); if (TextCommunityScore != null) { BindingTools.SetBinding(TextCommunityScore, TextBlock.TagProperty, GetGameBindingPath(nameof(GamesCollectionViewEntry.CommunityScoreRating))); } SetGameItemTextBinding(ref TextCriticScore, "PART_TextCriticScore", nameof(GameDetailsViewModel.Game.CriticScore), nameof(GameDetailsViewModel.CriticScoreVisibility)); if (TextCriticScore != null) { BindingTools.SetBinding(TextCriticScore, TextBlock.TagProperty, GetGameBindingPath(nameof(GamesCollectionViewEntry.CriticScoreRating))); } SetGameItemTextBinding(ref TextUserScore, "PART_TextUserScore", nameof(GameDetailsViewModel.Game.UserScore), nameof(GameDetailsViewModel.UserScoreVisibility)); if (TextUserScore != null) { BindingTools.SetBinding(TextUserScore, TextBlock.TagProperty, GetGameBindingPath(nameof(GamesCollectionViewEntry.UserScoreRating))); } SetItemsControlBinding(ref ItemsGenres, "PART_ItemsGenres", nameof(GameDetailsViewModel.SetGenreFilterCommand), nameof(GamesCollectionViewEntry.Genres), nameof(GameDetailsViewModel.GenreVisibility)); SetItemsControlBinding(ref ItemsDevelopers, "PART_ItemsDevelopers", nameof(GameDetailsViewModel.SetDeveloperFilterCommand), nameof(GamesCollectionViewEntry.Developers), nameof(GameDetailsViewModel.DeveloperVisibility)); SetItemsControlBinding(ref ItemsPublishers, "PART_ItemsPublishers", nameof(GameDetailsViewModel.SetPublisherFilterCommand), nameof(GamesCollectionViewEntry.Publishers), nameof(GameDetailsViewModel.PublisherVisibility)); SetItemsControlBinding(ref ItemsCategories, "PART_ItemsCategories", nameof(GameDetailsViewModel.SetCategoryFilterCommand), nameof(GamesCollectionViewEntry.Categories), nameof(GameDetailsViewModel.CategoryVisibility)); SetItemsControlBinding(ref ItemsTags, "PART_ItemsTags", nameof(GameDetailsViewModel.SetTagFilterCommand), nameof(GamesCollectionViewEntry.Tags), nameof(GameDetailsViewModel.TagVisibility)); SetItemsControlBinding(ref ItemsFeatures, "PART_ItemsFeatures", nameof(GameDetailsViewModel.SetFeatureFilterCommand), nameof(GamesCollectionViewEntry.Features), nameof(GameDetailsViewModel.FeatureVisibility)); SetItemsControlBinding(ref ItemsLinks, "PART_ItemsLinks", nameof(GameDetailsViewModel.OpenLinkCommand), nameof(GamesCollectionViewEntry.Links), nameof(GameDetailsViewModel.LinkVisibility), nameof(Link.Url)); }
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)); }
/// <summary> /// Gets the status of the design mode /// </summary> /// <returns>TRUE if in design mode, else FALSE</returns> public bool GetIsInDesignMode() { return(DesignerProperties.GetIsInDesignMode(this)); }
private void HandleTheme() { if (this.DialogSettings != null) { Tuple <AppTheme, Accent> tuple = BaseMetroDialog.DetectTheme(this); if (DesignerProperties.GetIsInDesignMode(this) || tuple == null) { return; } AppTheme item1 = tuple.Item1; Accent item2 = tuple.Item2; switch (this.DialogSettings.ColorScheme) { case MetroDialogColorScheme.Theme: { ThemeManager.ChangeAppStyle(base.Resources, item2, item1); DependencyProperty backgroundProperty = Control.BackgroundProperty; Window owningWindow = this.OwningWindow; if (owningWindow == null) { owningWindow = Application.Current.MainWindow; } base.SetValue(backgroundProperty, ThemeManager.GetResourceFromAppStyle(owningWindow, "WhiteColorBrush")); DependencyProperty foregroundProperty = Control.ForegroundProperty; Window mainWindow = this.OwningWindow; if (mainWindow == null) { mainWindow = Application.Current.MainWindow; } base.SetValue(foregroundProperty, ThemeManager.GetResourceFromAppStyle(mainWindow, "BlackBrush")); break; } case MetroDialogColorScheme.Accented: { ThemeManager.ChangeAppStyle(base.Resources, item2, item1); DependencyProperty dependencyProperty = Control.BackgroundProperty; Window window = this.OwningWindow; if (window == null) { window = Application.Current.MainWindow; } base.SetValue(dependencyProperty, ThemeManager.GetResourceFromAppStyle(window, "HighlightBrush")); DependencyProperty foregroundProperty1 = Control.ForegroundProperty; Window owningWindow1 = this.OwningWindow; if (owningWindow1 == null) { owningWindow1 = Application.Current.MainWindow; } base.SetValue(foregroundProperty1, ThemeManager.GetResourceFromAppStyle(owningWindow1, "IdealForegroundColorBrush")); break; } case MetroDialogColorScheme.Inverted: { AppTheme inverseAppTheme = ThemeManager.GetInverseAppTheme(item1); if (inverseAppTheme == null) { throw new InvalidOperationException("The inverse dialog theme only works if the window theme abides the naming convention. See ThemeManager.GetInverseAppTheme for more infos"); } ThemeManager.ChangeAppStyle(base.Resources, item2, inverseAppTheme); DependencyProperty backgroundProperty1 = Control.BackgroundProperty; Window mainWindow1 = this.OwningWindow; if (mainWindow1 == null) { mainWindow1 = Application.Current.MainWindow; } base.SetValue(backgroundProperty1, ThemeManager.GetResourceFromAppStyle(mainWindow1, "BlackColorBrush")); DependencyProperty dependencyProperty1 = Control.ForegroundProperty; Window window1 = this.OwningWindow; if (window1 == null) { window1 = Application.Current.MainWindow; } base.SetValue(dependencyProperty1, ThemeManager.GetResourceFromAppStyle(window1, "WhiteColorBrush")); break; } } } if (this.ParentDialogWindow != null) { this.ParentDialogWindow.SetValue(Control.BackgroundProperty, base.Background); Window owningWindow2 = this.OwningWindow; if (owningWindow2 == null) { owningWindow2 = Application.Current.MainWindow; } object resourceFromAppStyle = ThemeManager.GetResourceFromAppStyle(owningWindow2, "AccentColorBrush"); if (resourceFromAppStyle != null) { this.ParentDialogWindow.SetValue(MetroWindow.GlowBrushProperty, resourceFromAppStyle); } } }
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); }
/// <summary> /// Shows the <see cref="Backstage"/> /// </summary> protected virtual bool Show() { // don't open the backstage while in design mode if (DesignerProperties.GetIsInDesignMode(this)) { return(false); } if (this.IsLoaded == false) { this.Loaded += this.OnDelayedShow; return(false); } if (this.Content == null) { return(false); } this.CreateAndAttachBackstageAdorner(); this.ShowAdorner(); var parentRibbon = GetParentRibbon(this); if (parentRibbon != null) { if (parentRibbon.TabControl != null) { parentRibbon.TabControl.IsDropDownOpen = false; parentRibbon.TabControl.HighlightSelectedItem = false; parentRibbon.TabControl.RequestBackstageClose += this.OnTabControlRequestBackstageClose; } // Disable QAT & title bar if (parentRibbon.QuickAccessToolBar != null) { parentRibbon.QuickAccessToolBar.IsEnabled = false; } if (parentRibbon.TitleBar != null) { parentRibbon.TitleBar.IsEnabled = false; parentRibbon.TitleBar.HideContextTabs = this.HideContextTabsOnOpen; } } var window = Window.GetWindow(this); if (window == null && this.Parent != null) { window = Window.GetWindow(this.Parent); } this.SaveWindowSize(window); this.SaveWindowMinSize(window); if (window != null) { window.KeyDown += this.HandleWindowKeyDown; if (this.savedWindowMinWidth < 500) { window.MinWidth = 500; } if (this.savedWindowMinHeight < 400) { window.MinHeight = 400; } window.SizeChanged += this.OnWindowSizeChanged; // We have to collapse WindowsFormsHost while Backstage is open this.CollapseWindowsFormsHosts(window); } var content = this.Content as IInputElement; content?.Focus(); return(true); }
public override void RuntimeInitialize(System.Reflection.MethodBase method) { methodName = method.Name; className = method.DeclaringType; try { var methods = className.GetMethods(); foreach (var m in methods) { if (m.Name == "RaisePropertyChanged") { this.method = m; } } } catch (Exception e) { if (Application.Current != null && Application.Current.MainWindow != null && !DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow)) { throw e; } } }
// http://stackoverflow.com/questions/834283/is-there-a-way-to-check-if-wpf-is-currently-executing-in-design-mode-or-not public static bool GetIsInDesingMode(this DependencyObject dependencyObject) { return(DesignerProperties.GetIsInDesignMode(dependencyObject)); }
public override void OnApplyTemplate() { base.OnApplyTemplate(); _popup = GetTemplateChild("PART_Popup") as Canvas; _border = GetTemplateChild("PART_Border") as Border; _root = GetTemplateChild("RootElement") as Grid; _callout = GetTemplateChild("Callout") as Callout; if (_root == null) { return; } _fadeStoryboard = ((Storyboard)_root.TryFindResource("FadeBorderAnimation")); if (_border == null || _callout == null || _popup == null) { return; } if (DesignerProperties.GetIsInDesignMode(this)) { _popup.Visibility = Visibility.Visible; } _border.MouseEnter += (s, e) => { if (_popupCloseToken != null) { _popupCloseToken.Dispose(); _popupCloseToken = null; } if (_popup.Visibility == Visibility.Collapsed) { _popup.Visibility = Visibility.Visible; _fadeStoryboard.Begin(); } }; _border.MouseLeave += (s, e) => { _popupCloseToken = TimedMethod.Invoke(() => { _popup.Visibility = Visibility.Collapsed; _fadeStoryboard.Stop(); }).After(200).Go(); }; _callout.MouseEnter += (s, e) => { if (_popupCloseToken != null) { _popupCloseToken.Dispose(); _popupCloseToken = null; } }; _callout.MouseLeave += (s, e) => { _popupCloseToken = TimedMethod.Invoke(() => { _popup.Visibility = Visibility.Collapsed; _fadeStoryboard.Stop(); }).After(200).Go(); }; //#if !SILVERLIGHT // _popup.VerticalOffset = -32; // _popup.AllowsTransparency = true; // _popup.PopupAnimation = PopupAnimation.Fade; //#endif }
/// <summary> /// Performs the conversion of a valid SVG source file to the /// <see cref="DrawingGroup"/>. /// </summary> /// <returns> /// This returns <see cref="DrawingGroup"/> if successful; otherwise, it /// returns <see langword="null"/>. /// </returns> protected virtual DrawingGroup CreateDrawing() { Uri svgSource = this.GetAbsoluteUri(); DrawingGroup drawing = null; if (svgSource == null) { return(drawing); } try { string scheme = svgSource.Scheme; if (String.IsNullOrEmpty(scheme)) { return(null); } WpfDrawingSettings settings = new WpfDrawingSettings(); settings.IncludeRuntime = _includeRuntime; settings.TextAsGeometry = _textAsGeometry; settings.OptimizePath = _optimizePath; if (_culture != null) { settings.CultureInfo = _culture; } switch (scheme) { case "file": //case "ftp": //case "https": case "http": using (FileSvgReader reader = new FileSvgReader(settings)) { drawing = reader.Read(svgSource); } break; case "pack": StreamResourceInfo svgStreamInfo = null; if (svgSource.ToString().IndexOf("siteoforigin", StringComparison.OrdinalIgnoreCase) >= 0) { svgStreamInfo = Application.GetRemoteStream(svgSource); } else { svgStreamInfo = Application.GetResourceStream(svgSource); } Stream svgStream = (svgStreamInfo != null) ? svgStreamInfo.Stream : null; if (svgStream != null) { string fileExt = Path.GetExtension(svgSource.ToString()); bool isCompressed = !String.IsNullOrEmpty(fileExt) && String.Equals(fileExt, ".svgz", StringComparison.OrdinalIgnoreCase); if (isCompressed) { using (svgStream) { using (GZipStream zipStream = new GZipStream(svgStream, CompressionMode.Decompress)) { using (FileSvgReader reader = new FileSvgReader(settings)) { drawing = reader.Read(zipStream); } } } } else { using (svgStream) { using (FileSvgReader reader = new FileSvgReader(settings)) { drawing = reader.Read(svgStream); } } } } break; } } catch { if (DesignerProperties.GetIsInDesignMode(new DependencyObject()) || LicenseManager.UsageMode == LicenseUsageMode.Designtime) { return(drawing); } throw; } return(drawing); }
private void InitializeComponent() { this.MinWidth = 150; this.MinHeight = 150; // 设计时显示内容 if (DesignerProperties.GetIsInDesignMode(this)) { if (this.TopicDragInfo == null) { Topic.TopicDragInfo info = new Topic.TopicDragInfo(); Topic.TopicDragItem option1 = new Topic.TopicDragItem() { Id = 1, Title = "AAA", AnswerId = 5 }; Topic.TopicDragItem option2 = new Topic.TopicDragItem() { Id = 2, Title = "BBB", AnswerId = 6 }; Topic.TopicDragItem option3 = new Topic.TopicDragItem() { Id = 3, Title = "CCC", AnswerId = 7 }; Topic.TopicDragItem option4 = new Topic.TopicDragItem() { Id = 4, Title = "DDD", AnswerId = 8 }; Topic.TopicDragItem option5 = new Topic.TopicDragItem() { Id = 5, Title = "EEE", AnswerId = 1 }; Topic.TopicDragItem option6 = new Topic.TopicDragItem() { Id = 6, Title = "FFF", AnswerId = 2 }; Topic.TopicDragItem option7 = new Topic.TopicDragItem() { Id = 7, Title = "GGG", AnswerId = 3 }; Topic.TopicDragItem option8 = new Topic.TopicDragItem() { Id = 8, Title = "HHH", AnswerId = 4 }; info.LeftOption.Add(option1); info.LeftOption.Add(option2); info.LeftOption.Add(option3); info.LeftOption.Add(option4); // info.LeftOption.AddRange(new ObservableCollection<Topic.TopicDragItem> { option1, option2, option3, option4 }); info.RightOption.Add(option5); info.RightOption.Add(option6); info.RightOption.Add(option7); info.RightOption.Add(option8); // info.RightOption.AddRange(new ObservableCollection<Topic.TopicDragItem> { option5, option6, option7, option8 }); TopicDragInfo = info; } } this.Background = Brushes.LightCoral; this.SizeChanged += TopicDragControl_SizeChanged; }