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

WPF Data Binding Validation Rules

$
0
0

Hello everyone,

I'm studying for Windows Application Development exam and there is one thing about data binding validation rules that's bugging me.

I have a class Testor with a property that always returns "abc".

public class Testor
{    
    public Testor()
    {
    }
    public string Prop
    {
        get { return "abc"; }        
    }
}

I add the namespace in XAML, and instantiate an object of Testor: 

<Window.Resources><local:Testor x:Key="myTestor"></local:Testor></Window.Resources>

Then I bind its property "Prop" to a Label control - which correctly displays "abc". 

<Label Margin="192,113,199,162"><Label.Content><Binding Source="{StaticResource myTestor}" 
                 Path="Prop" 
                 NotifyOnValidationError="True"><Binding.ValidationRules><local:StringValidator/>  </Binding.ValidationRules></Binding></Label.Content></Label>

What I would like is to have validation of the bound "Prop" property. So I derive a class from ValidationRule like this:

public class StringValidator : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value.ToString() == "")
                return new ValidationResult(false, "String cannot be empty");
            return new ValidationResult(true, null);
        }
    }

And then I add it to XAML under Binding.ValidationRules.

Why does Validate() method never run? I'm clearly missing something but I can't figure it out.


{usercontrol (wpf)} listbox datasource and data template

$
0
0

dear all 

i'm create this project with vb.net 2010, and i wish create some listbox data template with usercontrol (wpf).

this picture hope just anyone can understand what i want:

can anyone give me some advice or some project can i follow ?? 

how to show load idication while sending email by using MailMessage and smtp

$
0
0

Hi Helpers,

While sending message with number of images attached to it its taking too much time and i am unable to show loading indication,

So can anybody help me out how to show loading image while sending message using "MailMessage and SMTP"

thans Regards

DateTimeUpDown custom format

$
0
0

Hi All.

Is it possible to specify custom format for DateTimeUpdown control like hhh:mm? If yes, how it to do?

Thanks.

How do I get my listview (datagrid) data from the screen after I have sorted the data on screen

$
0
0

I have a listview and a datagrid inside it that displays data on the screen. On the screen I can sort the data columns.

I want to be able to click a button and copy the data from the table on screen to the clipboard so that it can be pasted into Excel.

How would I do this? I have a button event and inside the even method I call the listview element which works as long as I don't sort the data. if I sort the data the listview object still has the data in the original order, its not sorted. How do I get the sorted data?


chuckdawit

Converting Canvas with Background to Image C#/WPF

$
0
0

I have a problem converting a canvas to a bitmap image in a C#/WPF app. Basically I have a canvas and the background of the canvas is a diagram of a piece of machinery. There are several coloured rectangles on the canvas which the user drags over the diagram to indicate areas of damage. My code redraws the rectangles on the fly as the mouse is moving and adds a rectangle as a child item when the mouse button is released. I then want to capture the diagram with the coloured rectangles as a new image to save to a DB. My problem is that when I convert it to a BMP all I see is the coloured rectangles with no background image. However, I need to see the rectangles and the background image together. Hope this is ok. Here is my code:

XAML for canvas and child rectangles:

    <Canvas Height="421" Name="canv1">
     <Rectangle.... etc/>
     <Rectangle.... etc/>
     <Rectangle.... etc/>
     <Rectangle.... etc/>
     <Rectangle.... etc/>
    </Canvas>

code to assign canvas backgound image :


    ImageBrush ib = new ImageBrush();
    ib.ImageSource = backgroundImage;
    canv1.background = ib;

my code to capture as bitmap (adapted from a post on stackoverflow)

    public void ExportToPng(string path, Canvas diagram)
    {
   
      Transform transform = diagram.LayoutTransform;
   
      diagram.LayoutTransform = null;
   
      Size size = new Size(diagram.ActualWidth, diagram.ActualHeight);
   
      diagram.Measure(size);
      diagram.Arrange(new Rect(size));
   
    
      RenderTargetBitmap renderBitmap =
        new RenderTargetBitmap(
          (int)size.Width,
          (int)size.Height,
          96d,
          96d,
          PixelFormats.Pbgra32);
      renderBitmap.Render(diagram);
   
   
      using (FileStream outStream = new FileStream( path, FileMode.Create))
      {
    
        PngBitmapEncoder encoder = new PngBitmapEncoder();
   
        encoder.Frames.Add(BitmapFrame.Create(renderBitmap));
   
        encoder.Save(outStream);
      }

many thanks for your help.

GridViewColumn.CellTemplate does not work for me

$
0
0

What I am doing wrong?

<ListView Grid.Row="3" Grid.ColumnSpan="2" ItemsSource="{Binding Data}"><ListView.View><GridView><GridViewColumn Header="Test Name" DisplayMemberBinding="{Binding Header}"><GridViewColumn.CellTemplate><DataTemplate><TextBlock Text="{Binding TestName}" /></DataTemplate></GridViewColumn.CellTemplate></GridViewColumn><GridViewColumn Header="Value" DisplayMemberBinding="{Binding [0]}" /></GridView></ListView.View></ListView>

TestName is a string property . It does not display a TestName in the cell but just Header.ToString(). Even more it does not complain if I change TestName in the TextBlock binding to something wrong.

Thank you.

PasswordBox binding in MVVM and attached property walkaround.

$
0
0
 

Hi All,

I have a little project where I need to get a password from a user. I did search the forum for the solution and there seem to be just 2 answers.

1. It is impossible to bind to Password property as it was kept by Microsoft as CLR property for security reasons, to avoid easy access to plain text password.

2. The second solution uses attached property as workaround to allow binding.

The arguments why Password property is not dependency property are pretty clear.

For the second option however I couldn't find anything mentioned about any introduced security risks. For example this article Pete O'Hanlon says that his solution is OK when there is no need for security however without any more details (and there are more articles like this). I am no security expert and I would like to understand more about the issue.

Q1. My thinking is that if the solution with attached property was secure Microsoft would have implemented it within the framework. Or is there something more to it?

Q2. What is the correct secure way to handle passwords from PasswordBox in MVVM (with or without breaking the pattern)?

Q3. What are the disadvantages\risks of using attached property solution?


How to use WPF SplashScreen class under .NET Framework 4.5 / Windows 8?

$
0
0
Hi,

I have a problem using the WPF SplashScreen class under Windows 8:
When shutting down the application while the splash screen is about to be displayed, the program crashes sporadically with the following call stack:
ChildEBP RetAddr  
010af7c8 749eeaeb KERNELBASE!RaiseException+0x6c
010af7e4 74acb6e4 clr!COMPlusThrowBoot+0x1a
010af7f0 747d2823 clr!UMThunkStubRareDisableWorker+0x25
010af818 751d77d8 clr!UMThunkStubRareDisable+0x9
010af844 751d78cb USER32!InternalCallWinProc+0x23
010af8c0 751d7b6f USER32!UserCallWinProcCheckWow+0x100
010af924 751d7c44 USER32!DispatchClientMessage+0x15d
010af960 77962f02 USER32!__fnDWORD+0x2b
010af974 018541a0 ntdll!KiUserCallbackDispatcher+0x2e
WARNING: Frame IP not in any known module. Following frames may be wrong.
010af9c8 7693ddf8 0x18541a0
010afa18 7693e02a combase!CCliModalLoop::MyPeekMessage+0x5f [d:\win8_gdr\com\combase\dcomrem\callctrl.cxx @ 2316]
010afa8c 7693e0ca combase!CCliModalLoop::HandleWakeForMsg+0x15a [d:\win8_gdr\com\combase\dcomrem\callctrl.cxx @ 1954]
010afadc 76938d8d combase!CCliModalLoop::BlockFn+0x25b [d:\win8_gdr\com\combase\dcomrem\callctrl.cxx @ 1618]
010afb88 76938c23 combase!ClassicSTAThreadWaitForHandles+0xd7 [d:\win8_gdr\com\combase\dcomrem\classicsta.cpp @ 46]
010afbb0 748b3e82 combase!CoWaitForMultipleHandles+0xa4 [d:\win8_gdr\com\combase\dcomrem\sync.cxx @ 120]
010afc08 748b3e27 clr!MsgWaitHelper+0x64
010afc94 7494e825 clr!Thread::DoAppropriateWaitWorker+0x224
010afd00 7494e984 clr!Thread::DoAppropriateWait+0x64
010afd4c 74852f14 clr!CLREventBase::WaitEx+0x128
010afd64 749823f0 clr!CLREventBase::Wait+0x1a
010afde0 7498243d clr!IsRuntimeStarted+0xab
010afdec 749825e4 clr!WaitForEndOfShutdown+0x1b
010afe30 74945611 clr!EEShutDown+0xd1
010afe3c 7494566e clr!DisableRuntime+0x118
010afe50 74921fc2 clr!EEPolicy::HandleExitProcess+0x50
010afe90 74924162 clr!_CorExeMainInternal+0x1b1
010afecc 74e7f5a3 clr!_CorExeMain+0x4d
010aff04 74ef7efd mscoreei!_CorExeMain+0x10a
010aff1c 74ef4de3 MSCOREE!ShellShim__CorExeMain+0x7d
010aff24 74ff8543 MSCOREE!_CorExeMain_Exported+0x8
010aff30 7797ac69 KERNEL32!BaseThreadInitThunk+0xe
010aff74 7797ac3c ntdll!__RtlUserThreadStart+0x72
010aff8c 00000000 ntdll!_RtlUserThreadStart+0x1b
The crash does not happen all the time, only every now and then.

Here a simple example program to reproduce the problem:

App.xaml.cs file:
using System;
using System.Threading;
using System.Windows;

namespace SplashScreenTest
{
    public partial class App : Application
    {
        private void App_Startup(object sender, StartupEventArgs e)
        {
            SplashScreen splash = new SplashScreen("Splash.png");
            splash.Show(false);

            Thread.Sleep(1000);

            splash.Close(new TimeSpan(0,0,0,3));
            this.Shutdown();
        }
    }
}

App.xaml file:
<Application x:Class="SplashScreenTest.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="App_Startup"><Application.Resources></Application.Resources></Application>

You can use any PNG file as Splash.png.

Is there anything wrong in the way I am using the SplashScreen class?

(Please note: the crash does not happen if the timespan is reduced to zero; this can be used as a workaround. But still, a crash should not happen with a non-zero timespan.)

Problem with nested markup extensions

Graphic heavy UI using WPF

$
0
0

We have traditionally used Windows Forms to build very graphical UI applications.   Borderless windows with non-square image backgrounds and then use images for all controls including sliders, checkboxes, Radio buttons, buttons etc.   To provide a very rich and artistic GUI.   Most of the GUI designs are more small utility programs that the user pops up from a tool tray and then sets some values and exits.  Others are more robust with a lot of controls that user would use throughout the day for a specific task and but might be also used in a demo room on a big screen to show off technology.  A couple of problems with this is that scaling the graphical application for screen size is very difficult to do programatically.   The other is alpha blended edges that appear smooth and blend into the desktop is also hard to do with traditional Windows Forms.  The otehr issue is the complex creation and maintenance of custom controls to accoplish the look of the graphical controls.   This and many other reasons is why we'd like to move to WPF.  But I am trying to find good examples of how to do a Grapic heavy application in WPF?  I have seen many of the getting started Hello World example which basically show how to do simple windows forms type applications with a window and controls on it but not many examples of how to do graphical UI's.  A good example would be a media player like WinAMP with graphic skins for the UI as a WPF application?   

Any suggestions on where to look for help learning WPF for this case?


Jeff Davis

How to set initial focus to a textbox with gotfocus method in mvvm arch with xaml c# wpf 4.5

$
0
0

Hi,

I have create a page/window with many images and a few textbox's and buttons. When the app starts up and the page loads, I want to set the initial focus to the first textbox(the default focus is on images as they are the first loading elements) and change the focus to next elements.

I see wpf 4.5 only supports gotfocus() and lostfocus() events to set them but with an MVVM arch --> I do not want to have any code-behind till its absolutely necessary and also I  do not want to set the focus in the OnLoaded(). Any suggestions on how to do it?

Thanks in advance!

XAML Trigger or Condition Within Another Trigger

$
0
0

This seems like a strange request, I know.  Why not just use MultiDataTrigger?  Here is the problem:

My custom UserControl, based on a CheckBox has a style which makes it look like a wheel (actually more like an octagon), with spokes.  Top of the octagon is yellow, while everything else is black, so we can see "where it is" in the rotation. 

When the checkbox is checked, a RotateTransform executes "forever", and the wheel spins, about 2 seconds per rotation.  This is done via a MultiDataTrigger causing a storyboard to run in its EnterActions.  

When the checkbox is unchecked, it rotates back to the 0 degrees position.  This is done by stopping the storyboard and running another storyboard which sets the angle to 0 degrees over about 1/4 second.  This is done in the ExitActions of the same MultiDataTrigger.

Here's the issue:  If the rotation is near the beginning (<90 degrees) the wheel jumps back to 0 degrees at a reasonable speed (1/4 second).  If it is farther along (say 270 degrees) in its rotation, it jumps back to 0 degrees VERY fast (over the same 1/4 second).  

I can tell the "End Rotation" storyboard to return it to 360 degrees instead of 0, so it doesn't appear to be jumping backwards, but then the same issue occurs if I stop it at only 10 degrees of rotation:  It jumps all the way around to 360 degrees VERY fast.

So, my thought is to figure out the current angle somehow during the exit actions, or when the checkbox is unchecked.  If the angle is less than 90 degrees, return to 0 degrees.  If the angle is more than 90 degrees, send it to 360 degrees.  This would minimize the fast jumping, I think.

So, that is my question.  Is there any way to sense the current angle in the context of the exit actions of the multidata trigger?

Thanks...


Ron Mittelman

Convert String to XML and bind to WPF ListBox.

$
0
0

Hi EveryOne

I need to convert a string to XML and bind it to ListBox. How can I do it?

string msg = "<Person><FName>Murali</FName><LName>Kumar</LName><FName>Ashok</FName><LName>Kumar</LName></Person>";

I want to Convert this string "msg" to a collection or an object or anything which I can bind to a control. I donot want to create any external files and reference that file.

Thanks in advance

Murali Mahendra Banala


Murali Mahendra Banala

Pass DataContext Down Through Objects in XAML

$
0
0

Hello guys,

I am trying to write a custom control and my problem is that the column does not not receive DataContext and therefore cannot do the binding.

My custom control looks like this:

class customControl:ItemsControl
{
  public ColumnCollection Columns { get; set; }
  ..
  ...
  .....
}


And my XAML looks like this:

<customControl ItemsSource={Binding employees}><customcontrol.Columns><columnCollection><column name={Binding colName1}/></columnCollection></costumControl.Columns></customControl>

Now the problem is that the column does not receive DataContext and cannot bind to the colName1 property which is in DataContext.

How do i solve this? How to pass down the DataContext to objects inside other objects inside other objects?


WPF+ MVVM: How to Make the WPF Application More Responsive ?

$
0
0

I have been asked a question:  There is big data need to be updated in UI and the big data updating will take a while and the same time users try to type in text in textbox. How to you ensure that user input have the highest priority over big data field update?

In code behind, one of solution would be using Dispatcher with a specific priority. This allows for both ordering of items by priority and deferring certain types of work until the system has time to handle them. (For example, some work items can be deferred until the system or application is idle.) .

In WPF and MVVM design pattern, I wonder how do we achieve that goal? When UI is idle, VM callOnPropertyChanged ("big data"). However, since the VM does not know about UI status, how VM detect UI is idle?

Does anyone know to how tothis case in MVVM? Thx!


JaneC





UI

$
0
0

Hello

I want this type of UI for my hotel booking application.

Can anyone guide me what control(s) should i use?

Please help.


Deepak Chhirang

How to Alternate color in ItemsControl without touching the (default/global) DataTemplate

$
0
0

Hi  there,

trying to grasp a fine difference:

have a default DataTemplate

<DataTemplate DataType="{x:Type local:MyType}">
  <Grid>
...here some cool stuff :)...
  </Grid
</DataTemplate>

have an ItemsControl

<ItemsControl ItemSource="{Binding some datalist of local:MyType}" AlternationCount="2">
  <ItemsControl.ItemContainerStyle>
    <Style>
      <Style.Triggers>
        <Trigger Property="ItemsControl.AlternationIndex" Value="0">
          <Setter Property= "how to set Background on Grid in DataTemplate"
                       Value="LightBlue"/>
        </Trigger>
      </Style.Triggers>
   </Style>
  </ItemsControl.ItemContainerStyle>
</ItemsControl>

As far as I've understood <ItemsControl.ItemContainerStyle/> would be the place to apply styles that style specific visual behaviours in respect to an ItemsControl (e.g. alternating line color).

I'm experiencing problems achieving my goal.

If I'd define the AlternationIndex-dependent coloring within theDataTemplate I could get it to work.

But somehow I believe that isn't the way it should be done.

Maybe some bright programmer can show me how to keep my DataTemplate "clean":

  • no ItemsControl.AlternationIndex-reference in DataTemplate,
  • pure xaml,
  • styling within <ItemsControl.ItemConstainerStyle/>

and still be able to alternate-color lines in an ItemsControl.

BTW, I've read how not to solve my problem because DataTemplate is adapted to ItemsControl (exactly what I am trying to prevent)

Thnx.


If you don't dig, you won't find it


(MVVM) - How To Bind to DataContext from ContextMenu within DataTemplate

$
0
0

Hey Everyone,

I have a ListBox that contains a bunch of business objects (Models).

My heirarchy is like this:

Window
-> ItemsControl {Groups}
--> Group
---> ListBox {People}
----> Person
-----> ContextMenu (Edit/Delete)


My Window's DataContext is my ViewModel containing the Edit/Delete Commands.

I've tried many different ways to bind to the Command on my Window's DataContext, such as:

This is within the DataTemplate for my "Person":

<MenuItemHeader="Edit"Command="{Binding Path=DataContext.EditResourceCommand, RelativeSource={RelativeSource AncestorType={x:Type v:ManageResourcesView}}}"/>

The error I receive is:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType=.UI.ViewModels.ManageResourcesViewModel', AncestorLevel='1''. BindingExpression:Path=DataContext.EditResourceCommand; DataItem=null; target element is 'MenuItem' (Name=''); target property is 'Command' (type 'ICommand')

The weird thing is... my DataTemplate for my "Group" has the following, which works...

SelectedItem="{Binding Path=DataContext.SelectedResource, RelativeSource={RelativeSource AncestorType={x:Type v:ManageResourcesView}}}"


Any help or advice would be greatly appreciated.

 

 

 


My educational lectures on C# and .Net in general (ranging from beginner level topics to advanced topics): mariocatch.wordpress.com

MVVM WPF Datagrid SelectedValue bind by view model ?

$
0
0

Hi,

anyone know how to change, the Datagrid SelectedValue By ViewModel.I can change it from the view and trigger onproperty chaged but

cannot change it from the viewmodel. I need to select different selection from View in Datagrid by ViewModel.

comments are highly appreciate.

Viewing all 18858 articles
Browse latest View live


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