Quantcast
Channel: Windows Presentation Foundation (WPF) forum
Viewing all 18858 articles
Browse latest View live

WPF Web Browser Script Error

$
0
0

Just I want to use SyntaxHighlighter with WebBrowser in WPF.But It gives me error. 

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
        wbMain.Navigated += new NavigatedEventHandler(wbMain_Navigated);
    }

    void wbMain_Navigated(object sender, NavigationEventArgs e)
    {
        SetSilent(wbMain, true); // make it silent
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        wbMain.Navigate(new Uri("... some url..."));
    }
}


public static void SetSilent(WebBrowser browser, bool silent)
{
    if (browser == null)
        throw new ArgumentNullException("browser");

    // get an IWebBrowser2 from the document
    IOleServiceProvider sp = browser.Document as IOleServiceProvider;
    if (sp != null)
    {
        Guid IID_IWebBrowserApp = new Guid("0002DF05-0000-0000-C000-000000000046");
        Guid IID_IWebBrowser2 = new Guid("D30C1661-CDAF-11d0-8A3E-00C04FC9E26E");

        object webBrowser;
        sp.QueryService(ref IID_IWebBrowserApp, ref IID_IWebBrowser2, out webBrowser);
        if (webBrowser != null)
        {
            webBrowser.GetType().InvokeMember("Silent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.PutDispProperty, null, webBrowser, new object[] { silent });
        }
    }
}


[ComImport, Guid("6D5140C1-7436-11CE-8034-00AA006009FA"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
private interface IOleServiceProvider
{
  [PreserveSig]
  int QueryService([In] ref Guid guidService, [In] ref Guid riid, [MarshalAs(UnmanagedType.IDispatch)] out object ppvObject);
}

How can I suppress script errors when using the WPF WebBrowser control?



This BackgroundWorker is currently busy and cannot run multiple tasks concurrently inside for loop c#

$
0
0

I get this error if I click a button that starts the backgroundworker multiple times inside for loop.

{"This BackgroundWorker is currently busy and cannot run multiple tasks
concurrently."}

How do I work my code properly in each and every loop ?

Form1.cs

private void CreateUserClick(object sender, RoutedEventArgs e)
{
    for (int i = 0; i < 5; i++)
    {
        User parameters = new User
        {
            user = UserTextBox.Text + i,
        };

        BackgroundWorker CreateUserWorker = new BackgroundWorker();

        CreateUserWorker.DoWork += new DoWorkEventHandler(DataWorkers.CreateUserWork);

        DataWorkers.InitiateWork(sender, CreateUserWorker, parameters);
    }
}

DataWorkers.cs

public class DataWorkers
{
    public static readonly BackgroundWorker CreateUserWorker = new BackgroundWorker();

    public static void HookUpWorkersLogic()
    {
        CreateAccountWorker.DoWork += CreateUserWork;
    }

    public static void InitiateWork(
        object sender,
        BackgroundWorker worker,
        WorkerParameters parameters = null)
    {
        StaticElements.InvokerButtons[worker] = new InvokerButton(sender);

        StaticElements.InvokerButtons[worker].Button.IsEnabled = false;
        StaticElements.InvokerButtons[worker].Button.Content = "Wait...";

        worker.RunWorkerAsync(parameters);
    }
}

I have made this change below in forloop, but still not wokring nor getting any exception after this change but application hangs up

BackgroundWorker createUserWorker = new BackgroundWorker();

createUserWorker.DoWork += new DoWorkEventHandler(DataWorkers.CreateUserWork);

DataWorkers.InitiateWork(sender, createUserWorker, parameters);

SE




Button in title bar

$
0
0
Does anyone know how to add a button in the title bar of a WPF Window?

Center Menu Items

$
0
0

Hi,

I have a Menu control in my window and I am adding Menu Items to the Menu control. I am trying to figure out how to center those Menu Items within my Menu. 

Here is a screenshot:

My Menu Items are 16 x 16 in size and my Menu control is 32 x 32 in size. I want the Menu Item's to sit snug inside the Menu control, VerticalAlignment doesn't seem to work in my Menu Item tags. I've also tried adding a Grid in my Menu control and putting the Menu Item's inside that Grid but then the Menu Item's aren't stacked horizontally anymore (they are placed on top of each other). 

Do I need to edit the Menu control Style or the Menu Item Style?


In .NET Framework 4.6.2 the FormattedText() is Obsoleted, There is an build error.

$
0
0

When I try to build the WPF project with .net framework 4.6.2, I got an error, Because the FormattedText() is Obsoleted as below: 

[Obsolete("Use the PixelsPerDip override", false)]    

   public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground);

The new override method is 

public FormattedText(string textToFormat, CultureInfo culture, FlowDirection flowDirection, Typeface typeface, double emSize, Brush foreground,double pixelsPerDip);

Q: How can I determine the pixelsPerDip ?

Q: How can I use old constructor without pixelsPerDip?, because the pixelsPerDip is useless for my project.

Focus textbox after async call

$
0
0

Hi, I have a strange problem. After using an asynchronous call, I can not do focus to a particular control (textbox in this example). If I comment the lines where asynchronous calls, the focus works perfectly. i'm use MVVM Light 5.3.0 Why? Thx!

<TextBox Grid.Row="0"
                         Grid.Column="1"
                         utilidades:FocusExtension.IsFocused="{Binding IsFocused}"
                         Text="{Binding Articulo.Codigo, UpdateSourceTrigger=PropertyChanged}" />


        private async void CargarRubros()
        {
            PrepareIsBusy();

            ShowIsBusyMessage = true;

            ActiveProgressRing = true;

            IsBusyCustomMessage("Cargando rubros...");

            try
            {
                Rubros =
                    await
                        Task.Factory.StartNew(() => new ObservableCollection<Rubro>(_rubroService.TodosLosSubrubros()));

                ActiveProgressRing = false;

                if (Rubros.Any())
                {
                    RubroSeleccionado = Rubros.First();
                }
                else
                {
                    IsBusyInfoMessage("No se encontraron rubros.");

                    await Task.Factory.StartNew(() => Thread.Sleep(2000));
                }
            }
            catch (Exception)
            {
                IsBusyErrorMessage("Error al intentar obtener los rubros.");

                ActiveProgressRing = false;

                await Task.Factory.StartNew(() => Thread.Sleep(2000));
            }
            finally
            {
                ShowIsBusyMessage = false;

                ResetMessageAndImage();

                PrepareIsBusy();

                IsFocused = true;
            }
        }

    public static class FocusExtension
    {
        public static bool GetIsFocused(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsFocusedProperty);
        }

        public static void SetIsFocused(DependencyObject obj, bool value)
        {
            obj.SetValue(IsFocusedProperty, value);
        }

        public static readonly DependencyProperty IsFocusedProperty =
            DependencyProperty.RegisterAttached(
                "IsFocused", typeof(bool), typeof(FocusExtension),
                new UIPropertyMetadata(false, null, OnCoerceValue));

        private static object OnCoerceValue(DependencyObject d, object baseValue)
        {
            if ((bool) baseValue)
            {
                ((UIElement) d).Focus();
            }
            else if (((UIElement) d).IsFocused)
            {
                Keyboard.ClearFocus();
            }
            return (bool)baseValue;
        }
    }
        private bool _isFocused;

        public bool IsFocused
        {
            get { return _isFocused; }
            set
            {
                _isFocused = value;
                RaisePropertyChanged("IsFocused");
            }
        }

NEW

I share a file with a sample project. I use NET4.0, 4.5 and 4.6.

With net4 I downloaded the extension "Microsoft.Bcl.Async" to use TaskEx.Run. Also had the same problem with "Task.Factory.StartNew".

https://mega.nz/#!71UXQLxJ!a87-8v1gDASRQRKOl4LlUGUwDSixrBUYipP2in8mPKA


Code Management

$
0
0

Hi,

I am still new to WPF and I am trying to get the hang of control templates, styles, triggers, etc. I am also trying to manage my code so things don't get messy and everything is maintainable in terms of styling elements.

I looking for some clarity on what a resource dictionary is as I feel I am using it in the wrong way. I am trying to work in a "modular" fashion by styling elements like buttons and tabs etc, in resource dictionaries, so I am not styling anything inline in my MainWindow.xaml.  

Can all my code for my elements live inside resource dictionaries (a button resource dictionary, a menu resource dictionary) instead if being inside my MainWindow.xaml?

By this I mean can I have a control template and style of a button in a resource dictionary and then reference that resource dictionary in my MainWindow.xaml when I create a button with the button tags?


WPF binding leak

$
0
0

I have been using WPF for some time, but I have not heard before now that there can be binding leaks in WPF. A few days ago some guy said that the following XAML "produces two binding leaks":

<TextBlock x:Name="textBlock" Content={Binding SomeProperty} />

assuming that there is some data context.

This sounds strange for me, so my question: is it true? And what are WPF binding leaks?



C# BitmapImage BitmapCacheOption issues when saving image

$
0
0

I'm running into a strange problem when loading BitmapImages from a URI, passing them through a CroppedBitmap and encoding / saving to an image in memory via a MemoryStream.

Code below:

System.Windows.Media.Imaging.BitmapImage bi = new System.Windows.Media.Imaging.BitmapImage(); bi.BeginInit(); // The BitmapCacheOption seems to be the source of the problem - // Setting it to OnLoad removes the issue but performance is 3-4x slower bi.CacheOption = System.Windows.Media.Imaging.BitmapCacheOption.None; bi.UriSource = new Uri(inputFile); bi.DecodePixelWidth = (int)imageViewBox[10]; bi.DecodePixelHeight = (int)imageViewBox[11]; bi.EndInit(); System.Windows.Media.Imaging.CroppedBitmap cbi = new System.Windows.Media.Imaging.CroppedBitmap(bi, new System.Windows.Int32Rect( (int)(imageViewBox[2] * imageViewBox[10]), (int)(imageViewBox[3] * imageViewBox[11]), (int)((imageViewBox[4] - imageViewBox[2]) * imageViewBox[10]), (int)((imageViewBox[5] - imageViewBox[3]) * imageViewBox[11]))); newImageSize = new Size(cbi.PixelWidth, cbi.PixelHeight); using (MemoryStream msOut = new MemoryStream()) { System.Windows.Media.Imaging.BmpBitmapEncoder enc = new System.Windows.Media.Imaging.BmpBitmapEncoder(); enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(cbi)); // Throws access violation exception intermittently when zoomed on some images enc.Save(msOut);

As commented in the code, the enc.Save line throws an AccessViolation exception intermittently (usually on larger images at 2 x zoom) when the BitmapCacheOption is set to None. Setting it to OnLoad resolves the issue. However, this is a performance critical part of the application, and OnLoad seems to hit performance by 3-400% which is not workable.

Even stranger, sometimes an exception is not thrown, and the image returned has regular vertical fault lines in it, as if it was missing a vertical line of pixels every n rows. Those missing pixels then get moved to the right hand of the image in a "compressed" mini-image!

Can anyone shed light on what might be happening here? I've tried using an OnDownload event handler, but it never seems to fire, and have tried testing for IsDownloading before proceeding with the rest of the method but it always returns false which seems to suggest that fully loading the image is not the issue here.

Peculiar behaviour when using TextBlock.TextEffects

$
0
0

I am facing an peculiar issue when I use TextBlock.TextEffects. I have three TextBlock control with Text property as follows, 1. ti 2. fi 3. zi I apply the following TextEffects to all three TextBlock,

TextEffectCollection textEffetcs = new TextEffectCollection();

TextEffect textEffect = new TextEffect();
textEffect.PositionStart = 1;
textEffect.PositionCount = 1;
textEffect.Foreground = Brushes.Transparent;

textEffetcs.Add(textEffect);
textBlock.TextEffects = textEffetcs;

From my understanding, this will make the second character invisible.
However I notice that it is not true for the following scenario. 1. If the character which I am trying to apply the effect is the character i. 2. and it is preceded by either character t or f 3. and the font family is Calibri Then the text effects does not work.

Has anyone notice this?


Datagrid doesn't delete row on delete key press

$
0
0

I made a WPF application and had a datagrid bound to a List<Table>.  I displayed the Name property of the table for each row. I used the CanUserDeleteRows option.  When I pressed the delete key, the row was deleted not only from the display, but my list.

Now I have refactored and I have a Dictionary<String,Table> instead.  I am displaying the Value.Name.

The Datagrid is displaying the proper information, but now when I press the delete key, nothing happens.

Is that how it is supposed to work, or am I missing something?

If I have to code the delete myself, how do I make that happen?

WPF and Windows 10 crash

$
0
0

Hello,

We have a WPF app that need to stay opened for a longer period of time (overnight) with different users that log on and off to the respective PC.

The WPF app uses Single Instance technique from here: http://blogs.microsoft.co.il/blogs/arik/SingleInstance.cs.txt

There is a strange crash happening only in the following situation:

1. OS is Windows 10

2. The following sequence of user sign in / sign off must happen:

  • Account A is starting the app and logs off or locks the PC.
  • Account B signs in during the night, works on the PC for a while and then logs off.
  • Account A signs in again in the morning. The app runs but is the UI is frozen/minimized. When clicked/ tried to be resized, the following error occurs:

    System.OutOfMemoryException: Insufficient memory to continue the execution of the program.
       at System.Windows.Media.Composition.DUCE.Channel.SyncFlush()
       at System.Windows.Interop.HwndTarget.UpdateWindowSettings(Boolean enableRenderTarget, Nullable`1 channelSet)
       at System.Windows.Interop.HwndTarget.UpdateWindowPos(IntPtr lParam)
       at System.Windows.Interop.HwndTarget.HandleMessage(WindowMessage msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Interop.HwndSource.HwndTargetFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)

I already reviewed these posts: 

  • http://stackoverflow.com/questions/1944577/win32-window-in-wpf/1965382#1965382
  • https://social.msdn.microsoft.com/Forums/vstudio/en-US/0dc4100a-be99-4682-b757-18249f728f2b/outofmemoryexception-when-resizing-window?forum=wpf
  • http://www.actiprosoftware.com/community/thread/3849/minimize-navbar-floating-window-size-out-of-m

I tried the suggestions from the above posts with no luck.

Also, I cannot reproduce the problem consistently. It seem that some time needs to pass between the logins so that the problem to appear.

Thanks for any suggestion that you have.

How Do You Delete a Certificate Using CertMgr.exe CertMgr ?

$
0
0
I'm developing a Full Trust WPF Web App to be distributed on a corporate network.
I have created certificates, and signed the app.
I need the certificates to be automatically installed (I've created bootstaps for other pre-requisites - and I am aware of the security implications).

I've created a windows setup project (in VS 2008) which has custom actions to install the certificate to the Trusted Publishers and Trusted Root Certification Authorities.

certmgr -add "[TARGETDIR]My.cer" -s -r localMachine Root
certmgr -add "[TARGETDIR]My.cer" -s -r localMachine TrustedPublisher

This works and the certificate appears in the certificate manager as expected.

- Now the bit that isn't working:

I've added these commands to the Uninstall in Custom Actions.

certmgr -del "My.cer" -c -s -r localMachine TrustedPublisher
certmgr -del "My.cer" -c -s -r localMachine Root

From the command line these commands return success but the certificate does NOT get removed/deleted.
This is obviously the same for the installer.

HOW DO YOU DELETE A CERTIFICATE?

DataGrid

$
0
0

I want do some code when i click buttom delete in DataGrid preview the row delete. When i click delete row delete  but event KeyDown not see this event

What event responded for this action??


Cannot create an istance of ChildView error

$
0
0

In my parent view, I embed child views. One of child view is called "SelectionView". So my xaml code:

<StackPanel Orientation="Vertical" HorizontalAlignment="Left" ><localViews:SelectionView DataContext="{Binding VmSelect, Mode=TwoWay}" Visibility="{Binding IsSelectionViewVisible,Converter={StaticResource BooleanVisibilityConverter}}"></localViews:SelectionView></StackPanel>

In the parent view model(MVVM). I have the property

  public SelectViewModel VmSelect
        {
            get
            {
                if (this.vmSelect == null)
                    this.vmSelect = new SelectViewModel();
                return this.vmSelect;
            }
            set
            {
                if (this.vmSelect != value)
                {
                    this.vmSelect = value;
                    this.OnPropertyChanged("VmSelect");
                }
            }
        }

Also in the child view model constructor. I have

public SelectViewModel()
        {
            InitializeViewModel();
        }
private void InitializeViewModel()
        {
            LoadMenuItems();
            currentTabIndex = 0;
            this.Date = Helper.MinimumDate;
  // blah
     }

In the code behind of child view. I have the constructor

 public SelectionView()
        {
            try
            {
                InitializeComponent();
                InitializeViewExtras();
            }

 private void InitializeViewExtras()
        {
            InitializeLoadEvent();
            myApp = Application.Current as App;
        }

 private void InitializeLoadEvent()
        {
            if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
            {
                this.Loaded -= SelectionView_Loaded;
                this.Loaded += SelectionView_Loaded;
            }
        }

My question is that I get the exception: Cannot create an instance of "SelectView". The details are

SelectionView..ctor()
So what is wrong?



How to develop MVVM scratch apllication

$
0
0

hi to all,

Please tell me , How to implement or scratch develop for MVVM application . 

give me any Demo .

Thnaks,

Aniruddha acharya


A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Any buddy tell me what difference between ICommand & Relay Coomand With example

$
0
0

Hi to all,

Any buddy tell me what difference between ICommand  &Relay  Coomand  With example 

Impliment in MVVM Project.

and Why we use this type of command in WPF

Thanks,

aniruddha acharya


A.Acharya Feedback to us Develop and promote your apps in Windows Store Please remember to mark the replies as answers if they help and unmark them if they provide no help.

Bind reference to object

$
0
0

Hello everybody,

In a C#/WPF application, I'd like to know if it's possible to pass the reference to an object's property asCommandParameter.
Usually, I do something like this to send parameter to a command :

<Button Content="Send" Command="{x:static MyCommands.Send}" CommandParameter={Binding Path=Property1}"/>

Is it possible to pass the reference to Property1 to initialize it from aICommand ?

In C#, it's easy with the keywoard out but in WPF ... :(

Thanks in advance for your suggestions.


Mouse.DirectlyOver returns the wrong UIElement in WPF

$
0
0
Hi All,

While i try to mouse over on the "Label" element , Mouse.DirectlyOver it returns the "TextBlock" as a result. Why it happen like this?

     private void Dynamic_Design_PreviewMouseMove(object sender, MouseEventArgs e)
        {
            if(e.LeftButton == MouseButtonState.Pressed)
            {
                 var uiElement = Mouse.DirectlyOver as UIElement;
            }
        }
Any idea on this..?


Thanks,
Sowndaiyan

using a wpf window in a class library project

$
0
0

Is it possible to use window (namespace System.Windows) in a library project?

I've tried to use some wpf controls in a library project, but the only control I can add is the UserControl.xaml (and I need to show some windows programmatically).

I've also tried to copy-paste a window into the dll project but I received the error:

 

Library project file cannot specify ApplicationDefinition element.

 

 

thanks

GHillo

Viewing all 18858 articles
Browse latest View live