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

EF6 Code-First and WPF Combo Box

$
0
0

I am having some unintended issues with my ComboBox in WPF.  I have a Job Entity setup in my code like this:

        public class Job
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string BidNumber { get; set; }
            public string Address { get; set; }
            public string Address2 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public int Zip { get; set; }
            [Required]
            public Status Status { get; set; }

        }

And the related Status Entity setup below:

        public class Status
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public ICollection<Job> Jobs { get; set; }
        }

My Combo Box is setup per below in XAML:

<ComboBox  x:Name="StatusMenu" ItemsSource="{Binding TheseStatus}" DisplayMemberPath="Name" SelectedItem="{Binding ThisJob.Status}" Grid.Column="2" Grid.Row="8" Grid.ColumnSpan="3" Margin="2" BorderBrush="#FFABADB3" Background="White"/>

The Combobox is populating the list of statuses, correctly, however, on my detail window, when I select the status, and call savechanges, instead of creating the link to the selected status, it is adding another status of the same name to the status table, and linking to it.  I am at a loss, and can't figure out what is going on.  Any ideas?


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/Prism 6/Unity 4 - using an EventAggregator (PubSub) to publish and subscribe events across multiple shells

$
0
0

Hi there,

We have an application that uses multiple shells (Prism) where a user would update data in a grid in a screen in one shell (ShellA), and we'd like to either reflect the changes in the grid or trigger reloading of the new data in the gird in another read-only version of this screen in another shell (ShellB).

Is there a way we can send PubSub events over multiple shells? Or send messages over multiple shells using Prism/Unity?

Here is the Main Shell's Bootstrap. The code that has been commented out has been tried, however, since each shell is getting their own copy of EventAggregator (PubSub), this approach will not work. Please see the existing CreateShell logic below:

protected override DependencyObject CreateShell()
        {
            return Container.Resolve<LoginView>();           
        }     

protected override void InitializeShell()
        {
            base.InitializeShell();

            Application.Current.MainWindow = (Window)this.Shell;
            Application.Current.MainWindow.Show();
            
            //var shellEventAggregator = new EventAggregator();
            //shellEventAggregator.GetEvent<MyEvent>().Publish();
            //Container.RegisterInstance<EventAggregator>(shellEventAggregator);
        }

Any help is greatly appreciated!

Kind regards.


Custom Non - Client Area's

$
0
0

Hi,

I have been trying to create my own custom window with my own caption buttons and header, etc. I have done some searching on the web and found the WPF Shell Integration Library, this doesn't seem to be maintained anymore though and only works with older versions of the .NET framework. Is there any other alternative for something similar to the WPF Shell Integration Library?

I still don't know everything the .NET framework has to offer, I've been checking out the API reference and I can't seem to find any answers there on how to make custom windows.  



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(Workers.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(Workers.CreateUserWork);

DataWorkers.InitiateWork(sender, createUserWorker, parameters);

SE



want to protect source code from reverse engineering

$
0
0

I have developed a wpf application. I have used some Encryption and Decryption logic within the code.

But the Encryption is of no use now because using few tools, I am easily able to decompile all the dll's and see native source code.

Can any one please help me to prevent/hide my code from reverse engineering.

I am using wix setup to build setup packages for the Windows platform.

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.

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.


Foreground of a custom control

$
0
0

Hi

I have a requirement to build in WPF a control which contains other controls (TextBlock, lines...) which the color of the control is gradient, meaning, items on the left are white, items in the middle are gray and items on the right are also white:

                    GradientStopCollection displayColors = new GradientStopCollection();
                    displayColors.Add(new GradientStop(new Color() { A = 255, R = 255, G = 255, B = 255 }, 0));
                    displayColors.Add(new GradientStop(new Color() { A = 255, R = 173, G = 174, B = 175 }, 0.5));
                    displayColors.Add(new GradientStop(new Color() { A = 255, R = 255, G = 255, B = 255 }, 1));
                    resultColor = new LinearGradientBrush(lColors, new System.Windows.Point(0, 0.5), new System.Windows.Point(1, 0.5));

Is it possible to do this that the text foreground (for example) will be dependent on the color at the location where it is in the control?

How draw custom shape with inkcanvas

$
0
0

I want to draw line or rectangle by Inkcanvas .I draw rectangle with custom render. The problem is there are many rectangles drawn when mouse moving.This is my code.

  class CustomDynamicRenderer : DynamicRenderer
    {
        [ThreadStatic]
        static private Brush brush = null;

        [ThreadStatic]
        static private Pen pen = null;

        private Point prevPoint;
        bool first;

        protected override void OnStylusDown(RawStylusInput rawStylusInput)
        {
            // Allocate memory to store the previous point to draw from.
            prevPoint = new Point(double.NegativeInfinity, double.NegativeInfinity);
            base.OnStylusDown(rawStylusInput);
            
        }

        protected override void OnStylusUp(RawStylusInput rawStylusInput)
        {
            first = false;
            base.OnStylusUp(rawStylusInput);
        }

        protected override void OnDraw(DrawingContext drawingContext,
                                       StylusPointCollection stylusPoints,
                                       Geometry geometry, Brush fillBrush)
        {
            // Create a new Brush, if necessary.
            if (brush == null)
            {
                brush = new LinearGradientBrush(Colors.Red, Colors.Blue, 20d);
            }

            // Create a new Pen, if necessary.
            if (pen == null)
            {
                pen = new Pen(brush, 2d);
            }

            if (!first)
            {
                prevPoint=(Point)stylusPoints[0];
                first = true;
            }

            drawingContext.DrawRectangle(null, pen,  new Rect(prevPoint,(Point)stylusPoints[stylusPoints.Count-1]));
          
        }
    }

not mapped field getter, setter

$
0
0

hi,

i have added a computed field named PASSWORD

  public partial class APP_USERS : INotifyPropertyChanged
    {
        [NotMapped]
        public string PASSWORD
        {
            get { return PasswordUtils.passwordDecrypt( CRYPTED_PASSWORD, "key"); }
            set { CRYPTED_PASSWORD = PasswordUtils.passwordEncrypt(PASSWORD, "key"); }
        }
    }

 and in my WPF UI databind to it like this

<TextBox Text="{Binding PASSWORD}" />

when i launch the app i have the decrypted password in the textbox so the getter is working, but if i try to change it

and soon i leave the textbox, the value go back to the original one .

any idea please ?

thanks nad good day.

Drawing Basic Shapes in WPF InkCanvas

$
0
0
Hi..I am working on a paint like application in wpf.I want the users to be able to add some drawings over images or plain surfaces.Also i want to draw some basic shapes like line,ellipse or a rectangle.I am trying to work with an inkcanvas,where i can do freehand drawing,but i cant draw shapes like in paint.Can anyone guide me and provide some clues on how to do it.Please help me on this.Any inputs will be greatly appreciated..

How to define custom TabItems and set properties

$
0
0

Hi,

I'd like to simplify my XAML-Code. By now i have a TabControl with looks like this

<TabControl><TabItem><TabItem.Header><Grid>
        ..columndefinitions..</Grid><Border Grid.Column="0" Background="{DynamicResource IconName1} .../><Label Grid.Column="1" Content="Content1" .../></TabItem.Header><...some Content...></TabItem><TabItem><TabItem.Header><Grid>
        ..columndefinitions..</Grid><Border Grid.Column="0" Background="{DynamicResource IconName2} .../><Label Grid.Column="1" Content="Content2" .../></TabItem.Header><...some Content...></TabItem>
...repeating for each tab Control...</TabControl>

I'd like to symplify it to look like that:

<TabControl><MyTabItem IconName="IconName1" ContentName="ContentName1"/><MyTabItem IconName="IconName2" ContentName="ContentName2"/></TabControl>

I'm not sure what's the right way to do this: create a custom control / custom tabitem derived from tabitem, use a style, use a itemtemplate or something different.

thx for any hint

regards

How to run BackgroundWorker process inside for loop for each iteration?

$
0
0

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

Original code which executes only once works perfect-

Form1.cs

privatevoidCreateUserClick(object sender,RoutedEventArgs e){User parameters =newUser{
                user =UserTextBox.Text+ i,};DataWorkers.InitiateWork(sender,DataWorkers.CreateUserWorker, parameters);}}

code change to work for execute CreateUserWork 5 times in forloop which will save username

Form1.cs

privatevoidCreateUserClick(object sender,RoutedEventArgs e){for(int i =0; i <5; i++){User parameters =newUser{
            user =UserTextBox.Text+ i,};BackgroundWorkerCreateUserWorker=newBackgroundWorker();CreateUserWorker.DoWork+=newDoWorkEventHandler(Workers.CreateUserWork);DataWorkers.InitiateWork(sender,DataWorkers.CreateUserWorker, parameters);}}

DataWorkers.cs

publicclassDataWorkers{publicstaticreadonlyBackgroundWorkerCreateUserWorker=newBackgroundWorker();publicstaticvoidStartUpLogic(){CreateAccountWorker.DoWork+=CreateUserWork;}publicstaticvoidInitiateWork(object sender,BackgroundWorker worker,WorkerParameters parameters =null){StaticElements.InvokerButtons[worker]=newInvokerButton(sender);StaticElements.InvokerButtons[worker].Button.IsEnabled=false;StaticElements.InvokerButtons[worker].Button.Content="Wait...";

        worker.RunWorkerAsync(parameters);}}publicstaticvoidCreateUserWork(object sender,DoWorkEventArgs e){//create new user}

Suggest me correct change.


SE

Custom WPF-validation rules crash designer

$
0
0

Hi,

we're encountering a strange issue with custom validation rules. When designing a WPF-UserControl everything is fine until with add custom made validation rules to any binding. Once we did that, the designer instantly crashes with a NullReferenceException. The displayed callstack ends in BindingExpressionBase.Validate.

We played around to narrow the problem down, but everything we learned is:

- Using build-in validation rules works
- The exception is not caused within the custom validation rule. We created a blank rule without any logic, always returning "Valid" and the problem occurs
- The exception occurs wether the rule is defined in the same or a different project.
- Commenting the validation rules out instantly restores the designer
- The validation rules do work as expected at runtime

Sample XAML-code:

<ComboBox
  DisplayMemberPath="Name"
  Margin="120 0 0 0"
  Name="SomeComboBox"><ComboBox.SelectedItem><Binding
      Mode="OneWayToSource"
      Path="SomePath"><Binding.ValidationRules><validationRules:NotNullValidationRule
         ValidationStep="RawProposedValue"
         /></Binding.ValidationRules></Binding></ComboBox.SelectedItem></ComboBox>

Exception details:

System.NullReferenceException
Object reference not set to an instance of an object.
   at System.Windows.Data.BindingExpressionBase.Validate(Object value, ValidationStep validationStep)
   at System.Windows.Data.BindingExpression.Validate(Object value, ValidationStep validationStep)
   at System.Windows.Data.BindingExpressionBase.UpdateValue()
   at System.Windows.Data.BindingExpression.Activate(Object item)
   at System.Windows.Data.BindingExpression.AttachToContext(AttachAttempt attempt)
   at System.Windows.Data.BindingExpression.MS.Internal.Data.IDataBindEngineClient.AttachToContext(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Task.Run(Boolean lastChance)
   at MS.Internal.Data.DataBindEngine.Run(Object arg)
   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)
   at System.Windows.Threading.DispatcherOperation.InvokeImpl()
   at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Windows.Threading.DispatcherOperation.Invoke()
   at System.Windows.Threading.Dispatcher.ProcessQueue()
   at System.Windows.Threading.Dispatcher.WndProcHook(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)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.<>c__DisplayClass5_0.<Main>b__0()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()

Any ideas?


Set Multiple Mask for MaskedTextBox

$
0
0

I am using the Extended WPF Toolkit MaskedTextBox. I need a way to change the mask for 3 diferent text length.

There is a way of doing this using the XAML? I was thinking if it is possible to set a style for the MaskedTextBox.

How could I achieve this?

Thanks.


Valdirnm

Can WPF Application run on ALL Microsoft platforms?

$
0
0

Say I have an application written by C# and uses WPF. Can this application run on all Microsoft's operating system?

including

  • Windows Desktop/Laptop (e.g. Win10, Win7...etc)
  • Windows Mobile
  • Windows Tablet

I also assume that there is NO additional plug-in required as it only needs .NET framework which is built-in in all current Microsoft's devices.



Hi all! ObjectDataProvider trouble

$
0
0

I am workning on a desktop app in WPF. I am new to WPF but trying to learn. I have a problem in my DataGrid datasource.

I am using ObjectDataProvider like this:

<ObjectDataProvider x:key="DP_SHP_Projects" ObjectType="{x:type sql:Act_Sharepoint}" MethodName="AllWebProjects/>

And for my DataGrid:

<DataGrid x:Name="..... ItemSource="{Binding Source="{StaticResource DP_SHP_Projects}" .../>

This working like a clock when connection to sql server is ok but when is not I get an exception and the Window is not showing or sometimes it is but it is totally blank. Why?

I have tried most things but not the right solution soo please hep.

// Regards Magnus

EF6 Code-First and WPF Combo Box

$
0
0

I am having some unintended issues with my ComboBox in WPF.  I have a Job Entity setup in my code like this:

        public class Job
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string BidNumber { get; set; }
            public string Address { get; set; }
            public string Address2 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public int Zip { get; set; }
            [Required]
            public Status Status { get; set; }

        }

And the related Status Entity setup below:

        public class Status
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public ICollection<Job> Jobs { get; set; }
        }

My Combo Box is setup per below in XAML:

<ComboBox  x:Name="StatusMenu" ItemsSource="{Binding TheseStatus}" DisplayMemberPath="Name" SelectedItem="{Binding ThisJob.Status}" Grid.Column="2" Grid.Row="8" Grid.ColumnSpan="3" Margin="2" BorderBrush="#FFABADB3" Background="White"/>

The Combobox is populating the list of statuses, correctly, however, on my detail window, when I select the status, and call savechanges, instead of creating the link to the selected status, it is adding another status of the same name to the status table, and linking to it.  I am at a loss, and can't figure out what is going on.  Any ideas?

Code First

$
0
0

 I have 2 class

    

 public class Task
    {
        public int TaskId { get; set; }
        public string Discription { get; set; }
        public SpentTime SpendTimeForTask { get; set; }
        public Task() { SpendTimeForTask = new SpentTime(); }

 public class SpentTime
    {
        public int SpentTimeId { get; set; }
        public DateTime AssumedStart { get; set; }    
        public Task Task { get; set; }

    }

I want. When delete Task cascade delete SpendTimes. I write this code.

 private void DBDeleteTask(Task task) {
            using (var db = new ApplicationDbContext()) {
                var query = (from q in db.Tasks where q.Discription==task.Discription select q).Single();
                var query2 = (from q in db.SpendTimes where q.Task.Discription == query.Discription select q).Single();
                db.Tasks.Remove(query);               
                db.SaveChanges();            
               }
        }

But Delete from dataBase only Task. SpendTimes not delete

Viewing all 18858 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>