TextBox1.Handle in WPF

where should i put the code:
IntPtr handle = new System.Windows.Interop.WindowInteropHelper(this).Handle;
and:
when i try to paste it in the constructor it tells me:
The best overloaded method match for 'System.Windows.Interop.WindowInteropHelper.WindowInteropHelper(System.Windows.Window)' has some invalid arguments
maybe i need to write it differently or add something?

If you put it in a constructor of a UserControl, you must get a reference to the window and pass this one to the constructor of the WindowInteropHelper class. You can get a reference to the parent window of a UserControl once the UserControl has been loaded
by handling the Loaded event for the UserControl like this:
public partial class UserControl1 : UserControl
public UserControl1() {
InitializeComponent();
IntPtr handle;
this.Loaded += (s, e) =>
Window window = Window.GetWindow(this);
handle = new System.Windows.Interop.WindowInteropHelper(window).Handle;
Please remember to mark helpful posts as answer to close your threads.

Similar Messages

  • How to get Handle for a Image Control in WPF

     I have to read an image from a camera dll function.
     the function takes  a handle of the UI element to display the images.
    I was able to get the image on the Windows picturebox by using its handle property.
    But when i try to do the same thing in WPF, i found problem to do so, as WPF has a single handle
    for all controls.
    if i pass that handle  it will display the image on the Window itself.
    but i want it on Image box.
    so my question is how can i assign the WPF handle i have to the Image box or how can i get the
    handle of the Image box.
    I am aware that controls dont have handles in WPF.
    but is it not possible to get the handle using interop?
    please help me its really urgent.nishant singh,Bangalore

    Hi,
    You can try this:
    HwndSource hwndSource = PresentationSource.FromVisual(YourImageControl) as HwndSource;  
    if (hwndSource != null)  
        handle = hwndSource.Handle;  
    Let me know if it works !
    HTH
    ThomasThomas Lebrun [MVP] - WPF/LINQ: http://blog.developpeur.org/tom - http://morpheus.developpez.com

  • WPF Error on certain PC's

    When I attempt to run the exe of the wpf application I created the application stops working and gives the following information:
    Problem signature:
      Problem Event Name: CLR20r3
      Problem Signature 01: Information.exe
      Problem Signature 02: 1.0.0.0
      Problem Signature 03: 54f54cff
      Problem Signature 04: System
      Problem Signature 05: 4.0.30319.34238
      Problem Signature 06: 53e450ed
      Problem Signature 07: 3f5d
      Problem Signature 08: 16a
      Problem Signature 09: System.Windows.Markup.XamlParse
      OS Version: 6.1.7601.2.1.0.256.48
      Locale ID: 1033
      Additional Information 1: 0a9e
      Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
      Additional Information 3: 0a9e
      Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
    I am quite new at this stuff and have no clue how to decipher any of this. Any help would be greatly appreciated!
    Thanks,
    Jesse

    Click the link below to a complete working sample for handlers.
    http://www.codeproject.com/Articles/90866/Unhandled-Exception-Handler-For-WPF-Applications
    Do them first then worry about the other possibilities later.
    Which are  listed here.
    http://stackoverflow.com/questions/1472498/wpf-global-exception-handler/1472562#1472562
    The code I posted will not just cut and paste 100%
    Because this bit here:
    System.IO.File.WriteAllText(realapp.GetIsolateStorageLocation() + "errors.xml", xmlString);
    Uses something to get isolatedstorage location.
    And the key piece of code for this is
    IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForAssembly();
    string FullPath = store.GetType().GetField("m_RootDir", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(store).ToString();
    https://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.getuserstoreforassembly%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
    Otherwise it's all standard stuff and you could google stuff on msdn.
    Like for example datacontractserializer
    https://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=vs.110).aspx
    Or I can paste all the usings out the top of that file I copied it from for you, but that'll be tomorrow.
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • WPF UI running in seperate runspace - able to set/get controls via synchronized hash table, but referencing the control via the hash table from within an event handler causes both runspaces to hang.

    I am trying to build a proof of concept where a WPF form is hosted in a seperate runspace and updates are handled from the primary shell/runspace. I have had some success thanks to a great article by Boe Prox, but I am having an issue I wanted to open up
    to see if anyone had a suggestion.
    My goals are as follows:
    1.) Set control properties from the primary runspace (Completed)
    2.) Get control properties from the primary runspace (Completed)
    3.) Respond to WPF form events in the UI runspace from the primary runspace (Kind of broken).
    I have the ability to read/write values to the form, but I am having difficulty with events. Specifically, I can fire and handle events, but the minute I try to reference the $SyncHash from within the event it appears to cause a blocking condition hanging both
    runspaces. As a result, I am unable to update the form based on an event being fired by a control.
    In the example below, the form is loaded and the following steps occur:
    1.) Update-Combobox is called and it populates the combobox with a list of service names and selects the first item.
    2.) update-textbox is called and sets the Text property of the textbox.
    3.) The Text value of the textbox is read by the function read-textbox and output using write-host.
    4.) An event handle is registered for the SelectionChanged event for the combobox to call the update-textbox function used earlier.
    5.) If you change the selection on the combobox, the shell and UI hangs as soon as $SyncHash is referenced. I suspect this is causing some sort of blocking condition from multiple threads trying to access the synchronized nature of the hash table, but I am
    unsure as to why / how to work around it. If you comment out the line "$SyncHash.TXT_Output.Dispatcher.Invoke("Send",[action]{$SyncHash.TXT_Output.Text = $Value})" within update-textbox the event handler will execute/complete.
    $UI_JobScript =
    try{
    Function New-Form ([XML]$XAML_Form){
    $XML_Node_Reader=(New-Object System.Xml.XmlNodeReader $XAML_Form)
    [Windows.Markup.XamlReader]::Load($XML_Node_Reader)
    try{
    Add-Type –AssemblyName PresentationFramework
    Add-Type –AssemblyName PresentationCore
    Add-Type –AssemblyName WindowsBase
    catch{
    Throw "Unable to load the requisite Windows Presentation Foundation assemblies. Please verify that the .NET Framework 3.5 Service Pack 1 or later is installed on this system."
    $Form = New-Form -XAML_Form $SyncHash.XAML_Form
    $SyncHash.Form = $Form
    $SyncHash.CMB_Services = $SyncHash.Form.FindName("CMB_Services")
    $SyncHash.TXT_Output = $SyncHash.Form.FindName("TXT_Output")
    $SyncHash.Form.ShowDialog() | Out-Null
    $SyncHash.Error = $Error
    catch{
    write-host $_.Exception.Message
    #End UI_JobScript
    #Begin Main
    add-type -AssemblyName WindowsBase
    [XML]$XAML_Form = @"
    <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Window.Resources>
    <DataTemplate x:Key="DTMPL_Name">
    <TextBlock Text="{Binding Path=Name}" />
    </DataTemplate>
    </Window.Resources>
    <DockPanel LastChildFill="True">
    <StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
    <Label Name="LBL_Services" Content="Services:" />
    <ComboBox Name="CMB_Services" ItemTemplate="{StaticResource DTMPL_Name}"/>
    </StackPanel>
    <TextBox Name="TXT_Output"/>
    </DockPanel>
    </Window>
    $SyncHash = [hashtable]::Synchronized(@{})
    $SyncHash.Add("XAML_Form",$XAML_Form)
    $SyncHash.Add("InitialScript", $InitialScript)
    $Normal = [System.Windows.Threading.DispatcherPriority]::Normal
    $UI_Runspace =[RunspaceFactory]::CreateRunspace()
    $UI_Runspace.ApartmentState = [System.Threading.ApartmentState]::STA
    $UI_Runspace.ThreadOptions = [System.Management.Automation.Runspaces.PSThreadOptions]::ReuseThread
    $UI_Runspace.Open()
    $UI_Runspace.SessionStateProxy.SetVariable("SyncHash",$SyncHash)
    $UI_Pipeline = [PowerShell]::Create()
    $UI_Pipeline.Runspace=$UI_Runspace
    $UI_Pipeline.AddScript($UI_JobScript) | out-Null
    $Job = $UI_Pipeline.BeginInvoke()
    $SyncHash.ServiceList = get-service | select name, status | Sort-Object -Property Name
    Function Update-Combobox{
    write-host "`nBegin Update-Combobox [$(get-date)]"
    $SyncHash.CMB_Services.Dispatcher.Invoke($Normal,[action]{$SyncHash.CMB_Services.ItemsSource = $SyncHash.ServiceList})
    $SyncHash.CMB_Services.Dispatcher.Invoke($Normal,[action]{$SyncHash.CMB_Services.SelectedIndex = 0})
    write-host "`End Update-Combobox [$(get-date)]"
    Function Update-Textbox([string]$Value){
    write-host "`nBegin Update-Textbox [$(get-date)]"
    $SyncHash.TXT_Output.Dispatcher.Invoke("Send",[action]{$SyncHash.TXT_Output.Text = $Value})
    write-host "End Update-Textbox [$(get-date)]"
    Function Read-Textbox(){
    write-host "`nBegin Read-Textbox [$(get-date)]"
    $SyncHash.TXT_Output.Dispatcher.Invoke($Normal,[action]{$Global:Return = $SyncHash.TXT_Output.Text})
    $Global:Return
    remove-variable -Name Return -scope Global
    write-host "End Read-Textbox [$(get-date)]"
    #Give the form some time to load in the other runspace
    $MaxWaitCycles = 5
    while (($SyncHash.Form.IsInitialized -eq $Null)-and ($MaxWaitCycles -gt 0)){
    Start-Sleep -Milliseconds 200
    $MaxWaitCycles--
    Update-ComboBox
    Update-Textbox -Value $("Initial Load: $(get-date)")
    Write-Host "Value Read From Textbox: $(Read-TextBox)"
    Register-ObjectEvent -InputObject $SyncHash.CMB_Services -EventName SelectionChanged -SourceIdentifier "CMB_Services.SelectionChanged" -action {Update-Textbox -Value $("From Selection Changed Event: $(get-date)")}

    Thanks again for the responses. This may not be possible, but I thought I would throw it out there. I appreciate your help in looking into this.
    To clarify the "Respond to control events in the main runspace"... I'm would like to have an event generated by a form object in the UI runspace (ex: combo box selectionchanged event) trigger a delegate within the main runspace and have that delegate in
    the main runspace update the form in the UI runspace.
    ex:
    1.) User changes selection on combo box generating form event
    2.) Event calls delegate (which I have gotten to work)
    3.) Delegate does some basic processing (works)
    4.) Delegate attempts to update form in UI runspace (hangs)
    As to the delegates / which runspace they are running in. I see the $synchash variable if I run get-var within a delegate, but I do not see the $Form variable so I am assuming that they are in the main runspace. Do you agree with that assumption?

  • Can't delete file after renaming due to Word file handle still present. Error staes document is still in use but it's really not. Worked fine in 2007 but not in 2010.

    I have some code associated with a Word Template. The template is opened, filled out and saved via a routing in vba. This all works fine in older 2007 version (which is version it was originally created in). Once this file is saved, the user can change the
    date in a text box and re-save document. The code saves using the new date for part of new file name and then deletes that older file from the server. It fails at the delete function because the newer version of word is not dropping the file handle from the
    first named file when user saves it to the new filename. In older version (2007) this handle was released as soon as file was saved to a different name. I can't seem to figure out how to release the old document filename so the old document file can be deleted.
    I hope I explained this well enough.
    Here's the code that woeked in version 2007 but fails in version 2010.
    Option Explicit
    Dim CAPEX01 As MSForms.ComboBox
    Dim CAPEX02 As MSForms.ComboBox
    Dim LocalPath As String
    Dim NetPath As String
    Dim OldPath As String
    Dim OldPathNet As String
    Dim DocName01 As String
    Dim DocName02 As String
    Dim DocName03 As String
    Dim DocName04 As String
    Dim DocName As String
    Dim DocNameold As String
    Dim TestDocName As String
    Dim filesys
    Dim newfolder
    Sub AutoOpen()
    ActiveDocument.ActiveWindow.View.Type = wdPrintView
    TestDocName = ActiveDocument.TextBox2
    OldPathNet = "\\yourPath\" & TestDocName & "\"
    End Sub
    Sub AutoNew()
    TestDocName = ActiveDocument.TextBox2
    OldPathNet = "\\yourPath\" & TestDocName & "\"
     ComboBox1.Locked = False
     ComboBox1.Enabled = True
     FillList1
     FillList2
     End Sub
    Sub DeleteOldDoc()
    OldPathNet = "\\yourPath\" & TestDocName ' & "\"
    DocNameold = OldPathNet & TestDocName & "-" & DocName02 & "-" & DocName03 & "-" & DocName04 & ".doc"
        If Not TestDocName = DocName01 Then
            Set filesys = CreateObject("Scripting.FileSystemObject")
        If filesys.FileExists(DocNameold) Then
            filesys.DeleteFile (DocNameold), True      
     'I get file permission error here
        End If
        End If
    If DocName01 <> "" Then
    If Not TestDocName = DocName01 Then
    If Not TestDocName = "" Then
        MsgBox "Project Proposal Has Been Moved From Year " & TestDocName & " To " & DocName01 & ""
    End If
    End If
    End If
    TestDocName = DocName01
    End Sub
    '''''''Document path functions''''''
    Sub chkpath()
    Set filesys = CreateObject("Scripting.FileSystemObject")
    If Not filesys.FolderExists("\\yourPath\") Then
       newfolder = filesys.CreateFolder("\\yourPath\")
    End If
    If Not filesys.FolderExists("\\yourPath\" & DocName01 & "\") Then
        newfolder = filesys.CreateFolder("\\yourPath\" & DocName01 & "\")
    End If
    End Sub
    ''''''Save Function''''''
    Private Sub CommandButton1_Click()
    DocName01 = ActiveDocument.TextBox2
    DocName02 = ActiveDocument.TextBox4
    DocName03 = ActiveDocument.TextBox1
    DocName04 = ActiveDocument.ComboBox1.Value
    chkpath
    NetPath = "\\yourPath\" & DocName01 & "\"
    DocName = NetPath & DocName01 & "-" & DocName02 & "-" & DocName03 & "-" & DocName04
    ActiveDocument.SaveAs2 FileName:=DocName, FileFormat:=wdFormatDocument
     ComboBox1.Locked = True
     ComboBox1.Enabled = False
     ComboBox2.Locked = True
     ComboBox2.Enabled = False
     TextBox1.Locked = True
     TextBox1.Enabled = False
     TextBox3.Locked = True
     TextBox3.Enabled = False
     TextBox4.Locked = True
     TextBox4.Enabled = False
     DeleteOldDoc
    End Sub
    Sub FillList1()
    Set CAPEX02 = ActiveDocument.ComboBox2
      With CAPEX02
          .AddItem "CASTING", 0
          .AddItem "HOT ROLLING", 1
          .AddItem "COLD ROLLING", 2
          .AddItem "FINISHING", 3
          .AddItem "PLANT GENERAL", 4
          .AddItem "MOBILE EQUIPMENT", 5
      End With
    End Sub
     Sub FillList2()
     Set CAPEX01 = ActiveDocument.ComboBox1
      With CAPEX01
          .AddItem "A Name", 0
          .AddItem "Another Name", 1
      End With
    End Sub
    Private Sub CommandButton2_Click()
        UserForm1.Show
    End Sub

    mogulman52 and Don,
    I went back and looked at my code and had already updated it to SaveAs in the new docx format. It still holds the lock handle in place until Word closes, unlike earlier versions which released the lock handle when you did a SaveAs.
    As a note, all my Word and Excel macro-enabled (dotm & xltm) templates are read only and are never filled in, prompting the user for a file name on any close event or if they run the code gets auto-named. I do the SaveAs and concatenate the file name
    from data on the document (or sheet) that has been filled in. During the SaveAs the docx gets saved to a network folder and also on a local folder. The lock gets renamed to the filename and remains until Word is closed.
    So my code still fails at the point noted below while trying to delete an old filename version after the file has been saved as a new filename in a new folder. So....
    The code is looking in the last folder where the docx file was saved for the older filename so it can be deleted. The newest docx version has already been saved in a different folder and has a new lock handle of its own. That lock is not my problem, it's
    the older file lock which really exists in the same folder as the first filename that the docx was saved to. It does not release that lock until I exit Word. My work around has been to instruct all users to manually delete the older version file.
    The other odd thing is this only happens when I run it from code, if you manually go through these steps with the SaveAs menu drop-downs in Word it will release the lock handle???
    Hope this isn't to confusing and thanks for all your suggestions and help.
    Sub DeleteOldDoc()
    OldPathNet = "\\yourPath\" & TestDocName ' & "\"
    DocNameold = OldPathNet & TestDocName & "-" & DocName02 & "-" & DocName03 & "-" & DocName04 & ".doc"
    If Not TestDocName = DocName01 Then
    Set filesys = CreateObject("Scripting.FileSystemObject")
    If filesys.FileExists(DocNameold) Then
    filesys.DeleteFile (DocNameold), True 'I get file permission error here- lock handle is still present from last SaveAs command in last folder where previous version of file was saved.
    End If
    End If
    If DocName01 <> "" Then
    If Not TestDocName = DocName01 Then
    If Not TestDocName = "" Then
    MsgBox "Project Proposal Has Been Moved From Year " & TestDocName & " To " & DocName01 & ""
    End If
    End If
    End If
    TestDocName = DocName01
    End Sub
    Glenn

  • Animated GIF in WPf

    Hello, how do i add an animated GIF into a frame in a WPF application
    and only show it when i press a button

    You need to add refrence of WindowsFormsIntegration and System.Windows.Forms DLLs to your project. The following code will load gif file:
    <wfi:WindowsFormsHost
    xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
    xmlns:winForms="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms">
    <winForms:PictureBox x:Name="pictureBox" ImageLocation="C:\Images\progressbar.gif">
    </winForms:PictureBox>
    </wfi:WindowsFormsHost>
    If you need button click, then on button click handler you need to load the image to PictureBox.
    <StackPanel>
    <Button Name="btnLoad" Click="btnLoad_Click">Load</Button>
    <wfi:WindowsFormsHost>
    <winForms:PictureBox x:Name="pictureBox">
    </winForms:PictureBox>
    </wfi:WindowsFormsHost>
    </StackPanel>
    private void btnLoad_Click(object sender, RoutedEventArgs e)
    pictureBox.ImageLocation = @"C:\Images\progressbar.gif";
    Manoj Mandal

  • Unable to connect multiple MAF components in a WPF host application

    I'm trying to connect my MAF component parts for the addin extensibility to work, however I'm getting certain errors while trying to build my add in store.
    string path = @"...\MyProject\Extensibility\Output";
    string[] errorList = AddInStore.Rebuild(path);
    that's the pipeline path, which looks like according to documentation:
    Extensibility\
    Output\
    AddIns
    AddInSideAdapters
    AddInViews
    Contracts
    HostSideAdapters
    My WPF host app DLL file is located under this directory:
    MyProject\WPFApp\bin\debug
    So, I'm unsure where to build my HostView. Currently the output is the pipeline root directory (Extensibility\Output)
    I have 4 errors in my errorList:
    While examining an assembly for pipeline segments, got a ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. File Name: ...MyProject\Extensibility\Output\AddInSideAdapters\AddInSideAdapters.dll
    2:
    Could not connect up a part in a pipeline to its neighbors: Contract Name: "IAddInContract" Location: "Contracts\Contracts.dll".
    3:
    Could not connect up a part in a pipeline to its neighbors: AddInBase Name: "AddInView" Location: "AddInViews\AddInViews.dll".
    4:
    Could not connect 2 valid add-in model parts.
    And the code of addin side adapter, contact and addin view respectively:
    [AddInAdapter]
    public class AddInSideAdapter : ContractBase, IAddInContract
    private AddInView view;
    public AddInSideAdapter(AddInView view)
    this.view = view;
    public void Initialize(IPluginHandler handler)
    view.Initialize(handler);
    public INativeHandleContract GetCustomUI()
    return FrameworkElementAdapters.ViewToContractAdapter(view.GetCustomUI());
    [AddInContract]
    public interface IAddInContract: IContract
    void Initialize(IPluginHandler handler);
    INativeHandleContract GetCustomUI();
    [AddInBase]
    public abstract class AddInView
    public abstract void Initialize(IPluginHandler handler);
    public abstract FrameworkElement GetCustomUI();
    They're output directories are ok, all building into the corresponding pipeline segments. I really cannot understand what's failing. Pipeline structure is ok, build paths of segments are ok (just not sure about the HostView and the host app). The path variable
    is ok, i just omitted the entire path for brevity

    Hi Mefhisto,
    >>”So, I'm unsure where to build my
    HostView. Currently the output is the pipeline root directory”
    I found some information about your problem in “Pipeline Development Requirements”,It said “The host application and the host view are typically deployed
    in the same directory. The pipeline directory can be in any location but is typically in the same directory as the host application.”This is the link of the document :
    https://msdn.microsoft.com/en-us/library/bb384240(v=vs.90).aspx. And there are several samples,you can refer to it for reference.
    http://clraddins.codeplex.com/wikipage?title=Samples&referringTitle=Home

  • Overriding DPI of images when displaying them in WPF

    Posting following because it might help someone else. It took me quite 
    while to figure this one out.
    I started learning C# and WPF recently. I hadn't had so much fun since the
    late 1990s when I learned Java.
    But I stumbled on one major irritant working on my project, a picture viewer.
    Contrary to just about every environment I've encountered, WPF insists on
    taking the DPI of images into consideration when displaying them. What I want
    is to display the images in some area of my app, pixel-for-pixel unless that
    results in the picture going beyond the frame, in which case the image
    needs to be scaled down so it fits. I don't want to have a larger image because
    the DPI is smaller than 96, and I don't want a smaller image because the DPI
    is higher than 96.
    As far as I'm concerned, DPI is more often than not a useless number. Two
    examples.
    1) My camera arbitrarily assigns a DPI value of 72 to all pictures it takes.
       But what "inches" are we talking about here? Obviously there is no answer
       to that question. So it's a meaningless number.
    2) If I scan a 35 mm color slide, I will probably do so at a DPI value of
       something like 2400, but I'd sure want to display the resulting image much
       larger. By default, WPF will show it at original size, totally useless.
       The DPI here is certainly meaningful, but not as a display parameter!
    I compared two images from same original (leware.net/photo/dpi.html),
    one resized to a DPI of 48, the other to a DPI of 192. In a hex editor,
    except for the one byte that encodes the DPI value, the two files are
    identical. It's the same image, with a different DPI value, but no other
    differences.
    So how do I get a WPF picture viewer to display images without taking their
    DPI into consideration? As every browser and viewer I know will do?
    At first, I thought that I would be able to do something like:
        BitmapImage img = new BitmapImage();
        img.BeginInit();
            img.UriSource = new Uri(somePathOrUrl);
            img.DpiX = 96.0;   // override
            img.DpiY = 96.0;
        img.EndInit();
    But DpiX and DpiY are "get" only, not "set". Yet, it's just a simple number,
    and changing it before WPF does anything with the image does not sound like a
    big challenge (even when waiting for DownloadCompleted event). It's almost as
    if the WPF designers decided that WPI was sooo important that they would never
    allow anyone to modify the value...
    The first approach I tried used RenderTargetBitmap (created at 96 DPI),
    DrawingVisual, DrawingContext classes. Seems quite complex. It worked, but
    I wouldn't call it elegant.
    After much browsing (and with improving understanding), I found a better approach.
    In simple terms, I set the Image's Width and Height to PixelWidth and PixelHeight
    (which essentially makes the resulting DPI to be 96), and I set the Image's
    MaxWidth and MaxHeight to the space available to the Image in the app, to force
    scaling if the source is too large. I used Stretch=Uniform. Code fragments below.
    The Image is placed in a UniformGrid container which provides the MaxWidth and
    MaxHeight, and which centers the Image inside.
    This approach is quite a bit more elegant, it removed nearly 100 lines of code
    from the app. I still think though that it's not as simple as it could be.
    I had also read about "DPI awareness", didn't really understand it, but it seems
    to deal with DPI of display device, not of source images.
    So two questions:
    1) Is there a even easier way, esp. a way to directly modify or ignore an image's
       DPI values before using it (without copying the image into some new bitmap)?
    2) Barring that, is there something simpler than above?
    Note that I'm fine with the application being otherwise DPI aware (fonts,
    buttons, &c).
    Thanks
    WPF code fragments of the trivial application I used to fine-tune the second
    approach. The two images are 160x100 pixels (but any pair of images smaller
    than the display will do the trick), one at DPI 48, one at DPI 192, and named
    IMG_6726s48.jpg and IMG_6726s192.jpg. The both show at the same size, as I
    wanted.
    To see the original problem as I experienced it, set Stretch=None and comment
    out the two pairs of lines that set image.Width and image.Height.
    XAML
    <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="512" Width="512">
        <Grid>
            <TextBlock Name="lpvMessage" Text="(messages)" Margin="2,2,10,0" VerticalAlignment="Top"  TextWrapping="NoWrap"/>
            <UniformGrid Name="grid" Margin="48,48,16,16" Background="LightGray" SizeChanged="gridSizeChanges">
                <Image Name="image" Stretch="Uniform" HorizontalAlignment="Center" VerticalAlignment="Center" MouseDown="onClickInImage"/>
            </UniformGrid>
            <Button Content="48" HorizontalAlignment="Left" Margin="10,68,0,0" VerticalAlignment="Top" Width="32" Click="buttonClick"/>
            <Button Content="192" HorizontalAlignment="Left" Margin="11,93,0,0" VerticalAlignment="Top" Width="32" Click="buttonClick"/>
        </Grid>
    </Window>
    XAML.CS
    namespace WpfApplication1
        public partial class MainWindow : Window
            public MainWindow()
                InitializeComponent();
                grid.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xF0, 0xF0, 0xF0)); // shows grid for testing
                changeImage("48");
            private void changeImage(string dpi)
                BitmapImage img = new BitmapImage();
                img.BeginInit();
                img.UriSource = new Uri("R:/IMG_6726s" + dpi + ".jpg"); // IMG_6726s48.jpg or IMG_6726s192.jpg.
                img.EndInit();
                image.Source = img;
                lpvMessage.Text = "Loading :/IMG_6726s" + dpi + ".jpg";
            private void onClickInImage(object sender, MouseButtonEventArgs e)
                BitmapImage isrc = image.Source as BitmapImage;
                image.Width = isrc.PixelWidth;       // "ignores" DPI
                image.Height = isrc.PixelHeight;
                image.MaxWidth = grid.ActualWidth;   // prevents scaling larger than 1:1
                image.MaxHeight = grid.ActualHeight;
                bool shifted = Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift);
                if (shifted)  // shift-click to toggle Stretch between Uniform and None
                    if (image.Stretch == Stretch.None)    image.Stretch = Stretch.Uniform;
                    else                                 
    image.Stretch = Stretch.None;
                lpvMessage.Text = "grid.ActualSize=" + grid.ActualWidth + "x" + grid.ActualHeight +
                    " image.ActualSize=" + image.ActualWidth + "x" + image.ActualHeight +
                    " isrc.PixelSize=" + isrc.PixelWidth + "x" + isrc.PixelHeight +
                    " image.Stretch->" + ((image.Stretch == Stretch.None) ? "None" : "Uniform");
            private void gridSizeChanges(object sender, SizeChangedEventArgs e)
                BitmapImage isrc = image.Source as BitmapImage;
                image.Width = isrc.PixelWidth;       // "ignores" DPI (redundant here
                image.Height = isrc.PixelHeight;
                image.MaxWidth = grid.ActualWidth;   // prevents scaling to larger than 1:1
                image.MaxHeight = grid.ActualHeight;
                lpvMessage.Text = "grid.ActualSize=" + grid.ActualWidth + "x" + grid.ActualHeight +
                    " image.ActualSize=" + image.ActualWidth + "x" + image.ActualHeight +
                    " isrc.PixelSize=" + isrc.PixelWidth + "x" + isrc.PixelHeight +
                    " image.Stretch->" + ((image.Stretch == Stretch.None) ? "None" : "Uniform");
            private void buttonClick(object sender, RoutedEventArgs e)
                Button b = sender as Button;
                string dpi = b.Content as string;
                changeImage(dpi);

    Being able to ignore DPI is all I'm asking for, and what I've always done for decades
    If the objective is to fill the Window, then yes, it's simple, as the following example of a thumbnail image shows:
    <Grid>
    <Image Source="http://leware.net/temper/42fp.jpg"/>
    </Grid>
    Result below. DPI doesn't matter, pixel sizes don't matter, the source fills the Image control, while respecting the proportions.
    But I don't want the image to fill the space available if it doesn't have enough pixels, it looks fuzzy and I don't like that.
    So I add Stretch=None to the Image control, and it solves my problem, the image is shown at a size that corresponds to its pixel size (63x87), centered.
    <Grid>
    <Image Source="http://leware.net/temper/42fp.jpg" Stretch="None"/>
    </Grid>
    The above two XAML fragments give the following results:
    The second is what I want. So Stretch=None, unless the image is larger than display area, in which case Stretch=Uniform.
    Now I try my two test images, also with Stretch=None because they are smaller than display area.
    These two images are both 160x100 pixels, and, when compared in a hex editor, differ
    only in the couple of bytes that store the DPI value (0x0030 vs 0x00c0),
    all the rest is the same.
    <Grid>
    <Image Source="http://leware.net/photo/IMG_6726s48.jpg" Stretch="None"/>
    </Grid>
    and
    <Grid>
    <Image Source="http://leware.net/photo/IMG_6726s192.jpg" Stretch="None"/>
    </Grid>
    Here's what I see:
    DPI obviously does matter here, much to my surprise. WPF's behavior was unexpected. That was my original problem.
    The DPI 48 image is enlarged by a factor of 2, the 192 DPI image is reduced by a factor of 2. What I want is in between, and the same for both images, a display based only on pixel sizes, like most browsers and picture viewers do.
    In other words, I want one image pixel to be one display pixel, downsized to fit if the image is too large, but never enlarged beyond 1:1 to fill the available space.
    I had a hard time figuring out how to get those two small images to show identically.
    I finally got what I wanted with the solution at the top of this thread (overriding size of Image control instead of DPI). I'm sharing because it might help someone else.
    Is there a better way to handle this when the DPI is arbitrary? Isn't there a way to just tell WPF to ignore images' DPI values or simply override it (force an image's DPI to 96)?
    Quite possibly I'm trying to do something which does not quite fit in the philosophy of WPF. Maybe I'm closer now, I'm still learning (this discussion is helping).
    I won't be surprised if my application misbehaves when the DPI of the display is not 96. Not a concern for now.

  • More Guru Winners for February 2015 in the WPF category and many others!

    It's been a busy week that also saw the
    TECHNET WIKI SUMMIT 2015
    Then we had the results for
    February's TechNet Guru competition ALSO posted!
    http://blogs.technet.com/b/wikininjas/archive/2015/03/19/technet-guru-february-2015.aspx
    Below is a summary of the medal winners for December. The last column being a few of the comments from the judges.
    Unfortunately, runners up and their judge feedback comments had to be trimmed from THIS post, to fit into the forum's 60,000 character limit, however the full version is available on TechNet Wiki in the link above.
    Some articles only just missed out, so we may be returning to discuss those too, in future blogs.
     BizTalk Technical Guru - February 2015  
    Steef-Jan Wiggers
    BizTalk Server 2013 R2 Instrumenting a custom pipeline component with ETW
    Mandi Ohlinger: "Always a fan of helping our custom pipeline users. Great addition to this group."
    Sandro Pereira: "Images, format, descriptions, code and topic are excellent once again good work Steef-Jan."
    Vignesh Sukumar
    BizTalk BAM (Business Activity Monitoring)
    Sandro Pereira: "Great job on this article! Well explained and nice pictures, however the article format need to be improved and some proofreading is need"
    Mandi Ohlinger: "Welcome to the 'I heart BAM' fan club. Nice job on this topic. A MUST read for new-to-BAM users. "
    Steef-Jan Wiggers
    BizTalk Server 2013 R2 Instrumenting BAM Activity Tracking with ETW
    Sandro Pereira: "Images, format, descriptions, code and topic are excellent once again good work Steef-Jan."
    Mandi Ohlinger: "ETW for BAM Activities - LOVE it. Nice use of the Framework. "
     Forefront Identity Manager Technical Guru - February 2015  
    Wim Beck
    FIM2010: Filter objects on export
    PG: "Simple, targeted but nice article, nice layout. "
    Søren Granfeldt: "Nice. Would be perfect with a complete code sample."
     Microsoft Azure Technical Guru - February 2015  
    saramgsilva
    Azure Mobile Services: How to see the log files in server
    JH: "Log files are one of the most important things in a production environment. This article shows hows you can do that for the Azure Mobile Services in a nice and easy way."
    Alan Carlos: "Great article!"
    Ed Price: "Very useful topic! These are a great set of articles!"
    saramgsilva
    Azure Mobile Services: How to see the WebConfig file published
    Ed Price: "Great detail and fantastic use of images! I love all the in-line links!"
    JH: "Sometimes it is hard to tell when working in a multi-environment what configuration was published to the Server. The article shows short and easy how to do that for the Azure Mobile Services."
     Miscellaneous Technical Guru - February 2015  
    Arleta Wanat
    Retrieve all site mailboxes in your Office 365 tenant
    Durval Ramos: "This article has a well content, images and code that help to understand the solution. It has References and was Translated into more two languages. Good job!"
    Richard Mueller: "Good links. A great tutorial."
    Andy ONeill
    Silverlight: No Need to BringIntoView
    Durval Ramos: "A well formatted article is easier and more pleasant to read. This script is useful"
    Richard Mueller: "Good demonstration of a new feature."
    Chen V
    PowerShell : Enable Auto Reply for Shared Mail Box
    Durval Ramos: " A good solution originated of TechNet Forum. The script and images make it easy to understand and ensure you get the best interest to reader."
    Richard Mueller: "Good documentation of this feature."
     SharePoint 2010 / 2013 Technical Guru - February 2015  
    Geetanjali Arora
    SharePoint Online : Performing Batch Operations using REST API
    KB: "Very well explained article on a new and much awaited feature. Although Andrew Connell already explained this topic in several posts, this article still contains added value."
    Ed Price: "I love the History section. The formatting is amazing. And the References and See Also sections at the bottom are great icing on the cake. This is an important topic that's done incredibly well!"
    Matthew Yarlett
    Using the SpellCheck Webservice with the TinyMCE Richtext Editor and
    AngularJS in Office 365
    KB: "I read this article with growing interest, it contains a lot of added value. Very well and in-depth explanation. "
    Ed Price: "Great scenario! Good use of images, code, detail, and References! Could possibly use a greater breakdown and explanation of the code. This article just gets more and more interesting and valuable as you read it! Great job!"
    Arleta Wanat
    SharePoint Online: Turn on support for multiple content types
    in a list or library using Powershell
    KB: "Really nice, interesting and detailed article!"
    Ed Price: "The Content Types section helps explain this a lot! I also love the downloads at the end. What a fantastic resource!"
     Small Basic Technical Guru - February 2015  
    Nonki Takahashi
    Small Basic: Key Input
    Michiel Van Hoorn: "Great improvement."
    RZ: "Very nice explanation and examples of key input handling"
    Ed Price - MSFT
    Small Basic: The History of the Logo Turtle
    RZ: "Turtle (Logo) was the first programming language for many, including perhaps some of the Small Basic prorammers. Nice article explaining the history."
    Michiel Van Hoorn: "A nice background article and hopefull inspiration for those who want to start in robotics"
    Nonki Takahashi
    Small Basic: TechNet Wiki Article List
    Michiel Van Hoorn: "This is great! Perfect as a local cache of the articles. "
    RZ: "A good example"
     SQL BI and Power BI Technical Guru - February 2015  
    Sylvain PONTOREAU
    PowerBI API in .Net
    RB: "Great walkthrough. Looking forward for the WP8 version of the app ;)"
    PT: "Sylvain, very nice job with this. This is a timely topic about an emerging product that has great potential. This is a very good example of a well-written post on an interesting subject with enough information to be valuable to a
    solution developer. I will personally take time to explore the Power BI API and use your examples. "
     SQL Server General and Database Engine Technical Guru - February 2015  
    Ronen Ariely
    SQL Server Books Online
    AM: "Thank you for sharing this with us. It is quite informative and let us get familiar with BOL after the change from previous versins."
    Ed Price: "Nice! A very helpful introduction to Books Online! It also tells my technical writer friends that their hard work is appreciated! =^)"
    Durval Ramos
    How to Collect Events and Errors on SQL Server
    Ed Price: "Fantastic solution! A great resource that's amazingly well written with formatting, clear parameters, images, References, and a See Also section! And it even comes in Portuguese! Great article!"
    AM: "Thank you for sharing this with us. A good source to learn about our SQL Server instances. "
     System Center Technical Guru - February 2015  
    MarkusEliasson
    Troubleshoot ID 32008: DPM cannot
    protect this SharePoint farm...
    Ed Price: "An important topic that's very clear with great formatting and a good use of an image!"
    t.c.rich
    Managing Priorities of Client Polices and A/V Policies in SCCM
    Ed Price: "I love the descriptions, breakdown of sections, and code formatting! Great article!" 
    Mr X
    How to copy SMSTS.log when a Task Sequence fails in SCCM
    Ed Price: "A very helpful table and a good contribution to the community! Mr X again thinks of important content gaps to fill!"
     Transact-SQL Technical Guru - February 2015  
    Saeid Hasani
    T-SQL: How the Order of Elements in the ORDER BY Clause Implemented in the Output Result
    Durval Ramos: "Very well structured and with examples that clarify how a T-SQL statement can change the data output order."
    Richard Mueller: "Good use of Wiki guidelines and great examples."
    Ronen Ariely
    Free E-Books about SQL and Transact-SQL languages
    Richard Mueller: "An excellent collection and a great idea."
    Durval Ramos: "A good initiative. Very useful !!!"
    Ricardo Lacerda
    Declare Cursor (Transact-SQL) versus Window with Over - Running Totals
    - Accumulated Earnings
    Durval Ramos: "The "Window function" sample was well presented, but it was unclear how the chart was generated."
    Richard Mueller: "A new idea that can be very useful. Grammar needs work"
     Visual Basic Technical Guru - February 2015  
    Emiliano Musso
    Genetic algorithm to solve 2D Mazes in Visual Basic
    MR: "Great article! Love to see an application for AI in a simple game"
    Durval Ramos: "This article is well documented with images and your code clarifying important details. It also has References, a very useful video and your project available for download in "MSDN Code" !"
    Richard Mueller: "Incredible concept and code. Grammar needs work."
    Paul Ishak
    MultiHeadedTrackBar Control
    Durval Ramos: "Very interesting article, with methods and properties well documented. Your project was available in "MSDN Code" which facilitates the understanding of solution."
    Richard Mueller: "Amazing work. Extensive code but with lots of comments. Needs a TOC"
    tommytwotrain
    Using Trigonometry to draw graphic curves in VB.NET part 2.
    MR: "Great continuation. Love the usage of the code for circle text"
    Durval Ramos: "The article is interesting, but It's need to work better commenting about assemblies referenced on project and also structure your content into sections."
    Richard Mueller: "Good tutorial and example code demonstrating basic concepts. Avoid first person."
     Visual C# Technical Guru - February 2015  
    Magnus (MM8)
    C#: Enumerating collections that change
    Jaliya Udagedara: "Great article. Has a thorough and to the point explanation of problem and the solution with code samples. Loved it!"
    Carmelo La Monica: "Very useful and exhaustive about errors at runtime in these circumstances. Congratulations"
    Andy ONeill
    c#: Practical Poly
    Carmelo La Monica: "Fantastic artcle. Very detailed and exhaustive, congratulations ."
    Jaliya Udagedara: "Definitely worth reading this. Explains somewhat advance topic along with a fundamental concept of programming. "
     Wiki and Portals Technical Guru - February 2015  
    Durval Ramos
    Wiki: Microsoft Short URLs Personalized by SXP
    PG: "Nice idea, lots of potential to grow, really needs some more community attention."
    Richard Mueller: "An excellent idea. Good use of Wiki guidelines."
     Windows Phone and Windows Store Apps Technical Guru - February 2015  
    Carmelo La Monica
    Windows Phone 8: control Nokia Maps (Part 3)
    JH: "Part 3 of the series how to work with the Nokia maps control. As the previous articles this one contains a lot of code snippets and some pictures. Good work!"
    Ed Price: "A great topic, a fantastic breakdown of sections with clear descriptions, and a nice mix of code formatting and helpful images! Another stellar article from Carmelo! Great job including the link back at the end to the portal
    article!"
     Windows PowerShell Technical Guru - February 2015  
    Richard Mueller
    Document Your Active Directory Organization
    Alan Carlos: "Wow! Great article, congratulations!!! Very detailed!"
    Chen V: "Excellent Article - I liked return to top as well."
    Ed Price: "Wow! It's like a professional whitepaper! It's a valuable topic that's done with intricate detail! I love the images, diagrams, code blocks, and it ends very well with more resources and Wiki articles! The article just keeps
    digging deeper and deeper! Awesome job on this!"
    DexterPOSH
    PowerShell + REST API : Invoke-RestMethod Gotcha
    Chen V: "Good Article. TOC might have made this more rich! "
    Ed Price: "This is a good topic with some great content. It could benefit from sections and a TOC, as well as a References and See Also sections at the end. The inline links are helpful. Could "
    DexterPOSH
    PowerShell Trick : Search & highlight text in MS Word
    Ed Price: "This is a great solution, with some helpful Q&A in the comments!"
     Windows Presentation Foundation (WPF) Technical Guru - February 2015  
    Andy ONeill
    Lookless Controls
    KJ: "WPF can definitely be confusing when devs first encounter it. Like the way you break it down."
    Ed Price: "Wow! Fantastic explanations that are very clear and deep! The images and code bring it to life!"
    Andy ONeill
    Only One Parent
    KJ: "Same iwith this one, good 101 intro"
    Ed Price: "Another great tip! I love the detail here as well! Those snippets help a lot!"
    Andy ONeill
    Bind to Current Item of Collection
    KJ: "Feel like this topic has a lot of coverage out there, but it can't hurt to hammer on databinding yet one more time :) "
    Ed Price: "Fantastic topic with great execution! Although these could benefit from References and See Also wiki sections at the end, the Inline links help a lot!"
     Windows Server Technical Guru - February 2015  
    Mr X
    Ping for Beginners
    Mark Parris: "A good introduction with additional content."
    JM: "Great article idea and an excellent article that will be useful to many, thanks for your contribution."
    Philippe Levesque: "Good article that show a usefull utility for basic troubleshooting"
    Richard Mueller
    Active Directory: Get-ADFineGrainedPasswordPolicy Default and Extended Properties
    Mark Parris: "An Interesting insight on FGPP and their extended properties."
    JM: "This is a good piece of detailed information about this PowerShell cmdlet, thanks for sharing."
    Philippe Levesque: "Great article ! Illustrating some cmdlet's output when a user got assigned policy versus a user with the default domain policy could be a good idea."
    Richard Mueller
    Active Directory: Get-ADServiceAccount Default and Extended Properties
    Mark Parris: "A useful nugget of information."
    JM: "More very useful information about an AD cmdlet, thanks!"
    Philippe Levesque: "Good article !"
    As mentioned above, runners up and comments were removed from this post, to fit into the forum's 60,000 character limit.
    You will find the complete post, comments and feedback on the
    main announcement post.
    Please join the discussion, add a comment, or suggest future categories.
    If you have not yet contributed an article for this month, and you think you can write a more useful, clever, or better produced wiki article than the winners above,
    THERE'S STILL TIME! :D
    Best regards,
    Pete Laker
    More about the TechNet Guru Awards:
    TechNet Guru Competitions
    #PEJL
    Got any nice code? If you invest time in coding an elegant, novel or impressive answer on MSDN forums, why not copy it over to
    TechNet Wiki, for future generations to benefit from! You'll never get archived again, and
    you could win weekly awards!
    Have you got what it takes o become this month's
    TechNet Technical Guru? Join a long list of well known community big hitters, show your knowledge and prowess in your favoured technologies!

    Congrats to Andy, Andy, and MORE ANDY!!!! =^)
     Windows Presentation Foundation (WPF) Technical Guru - February 2015  
    Andy ONeill
    Lookless Controls
    KJ: "WPF can definitely be confusing when devs first encounter it. Like the way you break it down."
    Ed Price: "Wow! Fantastic explanations that are very clear and deep! The images and code bring it to life!"
    Andy ONeill
    Only One Parent
    KJ: "Same iwith this one, good 101 intro"
    Ed Price: "Another great tip! I love the detail here as well! Those snippets help a lot!"
    Andy ONeill
    Bind to Current Item of Collection
    KJ: "Feel like this topic has a lot of coverage out there, but it can't hurt to hammer on databinding yet one more time :) "
    Ed Price: "Fantastic topic with great execution! Although these could benefit from References and See Also wiki sections at the end, the Inline links help a lot!"
    Ed Price, Azure & Power BI Customer Program Manager (Blog,
    Small Basic,
    Wiki Ninjas,
    Wiki)
    Answer an interesting question?
    Create a wiki article about it!

  • WPF How can I implement the INotifyPropertyChanged in a Three-tier architecture?

    I am a student and I am confused on using the INotifyPropertyChanged in a three-tier style of coding. Can you guys help me a bit with these?
    I have a solution named MetroAppProject. It is composed of four projects (I omitted the using clauses and references, just imagine they are there and are working fine):
    1. MetroApp.BluePrints - a class library composed of the classes in my sql db
    An example of my class
    namespace MetroApp.BluePrints
        public partial class Patient
            public long Id { get; set; }
            public string PatientNumber { get; set; }
            public string LastName { get; set; }
            public string FirstName { get; set; }
            public string MiddleName { get; set; }        
            public string AddressLine1 { get; set; }
            public Nullable<short> CityId { get; set; }
    public string CityName { get; set; }
            public Nullable<short> ProvinceId { get; set; }
    public string ProvinceName { get; set; }        
    Then the second project:
    2. MetroApp.DataAccess = a class library composed of methods that calls my sql procedures. I used the SqlHelper class which contains the connection strings and other stuffs.
    example class
    namespace MetroApp.DataAccess
        public class PatientDb
    public Patient Retrieve(PatientParams parameters)
                SqlCommand command = new SqlCommand();
                Patient singItem = new Patient();
                command.CommandText = "RetrievePatients";
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@Id", parameters.Id).Direction = ParameterDirection.Input;
                DataTable dt = SqlHelper.GetData(command);
                if (dt.Rows.Count > 0)
                    DataRow row = dt.Rows[0];
                    singItem.Id = TDefaultValue.GetInt(row["Id"].ToString());
                    singItem.PatientNumber = TDefaultValue.GetString(row["PatientNumber"].ToString());
                    singItem.LastName = TDefaultValue.GetString(row["LastName"].ToString());
                    singItem.FirstName = TDefaultValue.GetString(row["FirstName"].ToString());
                    singItem.MiddleName = TDefaultValue.GetString(row["MiddleName"].ToString());
                    singItem.AddressLine1 = TDefaultValue.GetString(row["AddressLine1"].ToString());
                    singItem.CityId = TDefaultValue.GetShort(row["CityId"].ToString());
                    singItem.CityName = TDefaultValue.GetString(row["CityName"].ToString());
                    singItem.ProvinceId = TDefaultValue.GetShort(row["ProvinceId"].ToString());
                    singItem.ProvinceName = TDefaultValue.GetString(row["ProvinceName"].ToString());
                return singItem;
            public List<Patient> RetrieveMany(PatientParams parameters)
                var items = new List<Patient>();
                var command = new SqlCommand();
                command.CommandText = "RetrievePatients";
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.AddWithValue("@Id", parameters.Id).Direction = ParameterDirection.Input;
                command.Parameters.AddWithValue("@PatientNumber", parameters.PatientNumber).Direction = ParameterDirection.Input;
                command.Parameters.AddWithValue("@LastName", parameters.LastName).Direction = ParameterDirection.Input;
                command.Parameters.AddWithValue("@FirstName", parameters.FirstName).Direction = ParameterDirection.Input;
                command.Parameters.AddWithValue("@MiddleName", parameters.MiddleName).Direction = ParameterDirection.Input;            
                command.Parameters.AddWithValue("@CityId", parameters.CityId).Direction = ParameterDirection.Input;
                command.Parameters.AddWithValue("@ProvinceId", parameters.ProvinceId).Direction = ParameterDirection.Input;
                DataTable dt = SqlHelper.GetData(command);
                foreach (DataRow row in dt.Rows)
                    var item = new Patient();
                    item.Id = TDefaultValue.GetLong(row["Id"].ToString());
                    item.PatientNumber = (row["PatientNumber"].ToString());
                    item.LastName = (row["LastName"].ToString());
                    item.FirstName = (row["FirstName"].ToString());
                    item.MiddleName = (row["MiddleName"].ToString());                
                    item.AddressLine1 = (row["AddressLine1"].ToString());
                    item.CityId = (short)row["CityId"].ToString();
                    item.CityName = (row["CityName"].ToString());
                    item.ProvinceId = (short)row["ProvinceId"].ToString();
                    item.ProvinceName = (row["ProvinceName"].ToString());
                    items.Add(item);
                return items;
            public bool Insert(Patient entity, int userId, ref bool doesExist)
                var command = new SqlCommand();
                try
                    command.CommandText = "AddPatient";
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@PatientNumber", entity.PatientNumber).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@LastName", entity.LastName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@FirstName", entity.FirstName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@MiddleName", entity.MiddleName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@AddressLine1", entity.AddressLine1).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@CityId", entity.CityId).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@ProvinceId", entity.ProvinceId).Direction = ParameterDirection.Input;
    command.Parameters.AddWithValue("@Id", entity.Id).Direction = ParameterDirection.Input;
                    command.Parameters.Add("@DoesExist", SqlDbType.Bit).Direction = ParameterDirection.Output;
                    int result = SqlHelper.ExecuteNonQuery(command);
                    doesExist = (bool)(command.Parameters["@DoesExist"].Value);
                    entity.Id = (int)(command.Parameters["@Id"].Value);
                    if (result == 0 || doesExist)
                        return false;
                    return true;
                catch (Exception)
                    return false;
            public bool Update(Patient entity, int userId, ref bool doesExist)
                var command = new SqlCommand();
                try
                    command.CommandText = "EditPatient";
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@PatientNumber", entity.PatientNumber).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@LastName", entity.LastName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@FirstName", entity.FirstName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@MiddleName", entity.MiddleName).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@AddressLine1", entity.AddressLine1).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@CityId", entity.CityId).Direction = ParameterDirection.Input;
                    command.Parameters.AddWithValue("@ProvinceId", entity.ProvinceId).Direction = ParameterDirection.Input;
    command.Parameters.AddWithValue("@Id", SqlDbType.Int).Direction = ParameterDirection.Output;
                    command.Parameters.Add("@DoesExist", SqlDbType.Bit).Direction = ParameterDirection.Output;
    doesExist = (bool)(command.Parameters["@DoesExist"].Value);
                    int result = SqlHelper.ExecuteNonQuery(command);
                    if (result == 0 || doesExist)
                        return false;
                    return true;
                catch (Exception)
                    return false;
    Then a business logic
    3. MetroApp.BusinessLogic = class libray for calling the methods from DataAccess
    namespace MetroApp.BusinessLogic
        public class PatientMgr
            #region Fields
            private readonly PatientDb _db;
            #endregion
            #region Properties
            public Patient Entity { get; set; }
            public List<Patient> EntityList { get; set; }
            public PatientParams Parameters { get; set; }
            #endregion
            #region Constructors
            public PatientMgr()
                _db = new PatientDb();
                Entity = new Patient();
                EntityList = new List<Patient>();
                Parameters = new PatientParams();
            #endregion
            #region Methods
    public Patient Retrieve(PatientParams parameters)
                return _db.Retrieve(parameters);
            public List<Patient> RetrieveMany(PatientParams parameters)
                return _db.RetrieveMany(parameters);
            public bool Insert(Patient entity, int userId, ref bool doesExist)
                return _db.Insert(entity, userId, ref doesExist);
            public bool Update(Patient entity, int userId, ref bool doesExist)
                return _db.Update(entity, userId, ref doesExist);
            #endregion
    Then the last one, the WPF GUI
    <UserControl x:Class="MetroDentProject.Pages.PatientDetailsPage"
                 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
                 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
                 xmlns:dims="clr-namespace:MetroAppProject.UserCons"
                 mc:Ignorable="d" 
                 d:DesignHeight="720" d:DesignWidth="1280">
        <Grid x:Name="MainGrid" >
            <Grid.RowDefinitions>
                <RowDefinition  Height="40"/>
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
                <RowDefinition  />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <GroupBox Grid.Column="0" Grid.Row="1" Grid.RowSpan="7" x:Name="DetailsGroupBox" Header="Patient Details" >
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="Id: " Grid.Column="1" Grid.Row="0" Visibility="Collapsed"/>
                    <TextBox x:Name="IdTextBox" Grid.Column="1" Grid.Row="1" Visibility="Collapsed"/>
                    <TextBlock x:Name="PatientNumberTextBlock" Text="Patient Number: " Grid.Column="0" Grid.Row="0" />
                    <TextBox x:Name="PatientNumberTextBox" Grid.Column="1" Grid.Row="0" IsReadOnly="True" IsReadOnlyCaretVisible="True"/>
                    <TextBlock Text="Last Name: " Grid.Column="0" Grid.Row="1" />
                    <TextBox x:Name="LastNameTextBox" Grid.Column="1" Grid.Row="1" />
                    <TextBlock Text="First Name: " Grid.Column="0" Grid.Row="2" />
                    <TextBox x:Name="FirstNameTextBox" Grid.Column="1" Grid.Row="2" />
                    <TextBlock Text="Middle Name: " Grid.Column="0" Grid.Row="3" />
                    <TextBox x:Name="MiddleNameTextBox" Grid.Column="1" Grid.Row="3" />
                </Grid>
            </GroupBox>
            <GroupBox x:Name="ContactDetailsGroupBox" Header="Contact Details" Grid.Column="1" Grid.Row="1" Grid.RowSpan="7">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition/>
                        <ColumnDefinition />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <TextBlock Text="Address: " Grid.Column="0" Grid.Row="0" Grid.RowSpan="2" />
                    <TextBlock Text="City: " Grid.Column="0" Grid.Row="2" />
                    <TextBlock Text="Province: " Grid.Column="0" Grid.Row="3"/>
                    <TextBox x:Name="AddressTextBox" Grid.Column="1" Grid.Row="0" Grid.RowSpan="2"
                             TextWrapping="Wrap"
                             AcceptsReturn="True"
                             VerticalScrollBarVisibility="Auto"
                             />
                    <ComboBox x:Name="CitiesComboBox"  Grid.Column="1" Grid.Row="2"  />
                    <ComboBox x:Name="ProvincesComboBox"  Grid.Column="1" Grid.Row="3" />
                </Grid>
            </GroupBox>
            <dims:FunctionButtonsControl x:Name="FunctionButtonsCon" Grid.Row="9" Grid.Column="0" Grid.ColumnSpan="2"
                                         ExecuteClick="FunctionButtonsCon_OnExecuteClick"
                                         UndoClick="FunctionButtonsCon_OnUndoClick"
                                         BackClick="FunctionButtonsCon_OnBackClick"
                                         DeleteClick="FunctionButtonsCon_OnDeleteClick"
                                         />
        </Grid>
    </UserControl>
    I apologize for the long post. As you can see, I don't use binding. Binding requires me to use INotifyPropertyChanged interface which I am not familiar. Can you at least make my project to implement the INotifypropertyChanged?
    Here is my sample code for the WPF page:
    public partial class PatientDetailsPage 
            readonly PatientMgr itemMgr = new PatientMgr();       
            public PatientParams CurrentPar = new PatientParams(); // for undoActionType _action = ActionType.Insert; // this is an enum from another project, ActionType.Insert, ActionType.Update
            public ActionType Action
                get { return _action; }
                set { _action = value; }
            public PatientDetailsPage()
                InitializeComponent();
                BindComboBoxes();
            #region Methods
            public void OnFragmentNavigation(FragmentNavigationEventArgs e)
            public void OnNavigatedFrom(NavigationEventArgs e)
            public void OnNavigatedTo(NavigationEventArgs e)
            {            Setup();
            public void OnNavigatingFrom(NavigatingCancelEventArgs e)
            public Patient GetPageEntity()
                Patient setEntity = new Patient();
                setEntity.Id = (long)IdTextBox.Text;
                setEntity.PatientNumber = PatientNumberTextBox.Text;
                setEntity.LastName = LastNameTextBox.Text;
                setEntity.FirstName = FirstNameTextBox.Text;
                setEntity.MiddleName = MiddleNameTextBox.Text;
                setEntity.AddressLine1 = AddressTextBox.Text;
                setEntity.CityId = (short)CitiesComboBox.SelectedValue);
                setEntity.ProvinceId = (short)ProvincesComboBox.SelectedValue;
                setEntity.StatusId = true;
                return setEntity;
            public void Setup()
                switch (Action)
                    case ActionType.Insert:
                        Clearer(); //clears all textboxes and set all comboboxes to default
                        this.PatientNumberTextBlock.Visibility = Visibility.Collapsed;
                        this.PatientNumberTextBox.Visibility = Visibility.Collapsed;
                        FunctionButtonsCon.ExecuteButton.Content = "Add";
                        FunctionButtonsCon.DeleteButton.IsEnabled = false;
                        FunctionButtonsCon.DeleteButton.Visibility = Visibility.Hidden;
                        break;
                    //**Setup Update
                    case ActionType.Update:CurrentPar.Id = (long)IdTextBox.Text;
                        LoadSingle(CurrentPar);
                        this.PatientNumberTextBlock.Visibility = Visibility.Visible;
                        this.PatientNumberTextBox.Visibility = Visibility.Visible;
                        FunctionButtonsCon.ExecuteButton.Content = "Save";
                        FunctionButtonsCon.DeleteButton.IsEnabled = true;
                        FunctionButtonsCon.DeleteButton.Visibility = Visibility.Visible;
                        break;                
                LastNameTextBox.CaretIndex = LastNameTextBox.Text.Length;
                IsVisibleChanged += AutoFocus;
            public void LoadSingle(PatientParams parameters)
                var entity = itemMgr.Retrieve(parameters); //calls the BusinessLogic
                IdTextBox.Text = (entity.Id);
                PatientNumberTextBox.Text = (entity.PatientNumber);
                LastNameTextBox.Text = (entity.LastName);
                FirstNameTextBox.Text = (entity.FirstName);
                MiddleNameTextBox.Text = (entity.MiddleName);
                AddressTextBox.Text = (entity.AddressLine1);
                CitiesComboBox.SelectedValue = (short)entity.CityId;
                ProvincesComboBox.SelectedValue = (short)entity.ProvinceId;
            public void Save(ActionType action, int userId)
                itemMgr.Entity = GetPageEntity();
                bool doesExist = false;
                switch (action)
                    case ActionType.Insert:
                        if (itemMgr.Insert((itemMgr.Entity), userId, ref doesExist))
                            System.Windows.Forms.MessageBox.Show("Successfully added a Patient!", "Patient Insertion");                  
                        else if (doesExist)
                            System.Windows.Forms.MessageBox.Show("Item already exists.", "Patient Insertion");
                        else
                            System.Windows.Forms.MessageBox.Show("Not all fields were filled in.", "Patient Insertion");
                        break;
                    case ActionType.Update:
                        if (itemMgr.Update(itemMgr.Entity, userId, ref doesExist))
                            System.Windows.Forms.MessageBox.Show("Successfully updated a Patient!", "Patient Modification");
                            itemMgr.Parameters.Id = itemMgr.Entity.Id;
                            Action = ActionType.Update;
                            Setup();
                        else if (doesExist)
                            System.Windows.Forms.MessageBox.Show("Item already exists.", "Patient Modification");
                        else
                            System.Windows.Forms.MessageBox.Show("Not all fields were filled in.", "Patient Modification");
                        break;                
            public void Clearer()
                IdTextBox.Clear();
                PatientNumberTextBox.Clear();
                LastNameTextBox.Clear();
                FirstNameTextBox.Clear();
                MiddleNameTextBox.Clear();
                CitiesComboBox.SelectedIndex = 0;
                ProvincesComboBox.SelectedIndex = 0;
                AddressTextBox.Clear();            
            public void BindComboBoxes()
                CitiesComboBox.ItemsSource = new BindingSource(CommonMgr.GetCitiesDropDown(), null);// the CommonMgr is a static class from another project. It works just fine
                CitiesComboBox.DisplayMemberPath = "Value";
                CitiesComboBox.SelectedValuePath = "Key";           
                ProvincesComboBox.ItemsSource = new BindingSource(CommonMgr.GetProvincesDropDown(), null);
                ProvincesComboBox.DisplayMemberPath = "Value";
                ProvincesComboBox.SelectedValuePath = "Key";
                CitiesComboBox.SelectedIndex = 0;
                ProvincesComboBox.SelectedIndex = 0;
            #endregion
            #region Events
            private void FunctionButtonsCon_OnExecuteClick(object sender, RoutedEventArgs e)
                Save(Action, SessionHelper.MyUser.Id); //SessionHelper.MyUser.Id
            private void FunctionButtonsCon_OnUndoClick(object sender, RoutedEventArgs e)
                if (Action == ActionType.Insert)
                    Clearer();
                    return;
            private void FunctionButtonsCon_OnBackClick(object sender, RoutedEventArgs e)
                Exiter();
            private void FunctionButtonsCon_OnDeleteClick(object sender, RoutedEventArgs e)
                var ans = System.Windows.Forms.MessageBox.Show("Are you sure you want to delete this entry?", "Patient Deletion", MessageBoxButtons.YesNo);
                if (!Equals(ans, System.Windows.Forms.DialogResult.Yes)) return;
                Action = ActionType.Delete;
                Save(Action, SessionHelper.MyUser.Id);
                Exiter();
            #endregion

    Hello Kokombads,
    I thought you are using MVVM from your title but it seems your project is just a simple WPF project. In that way, please check the following msdn article to know how to Implement Property Change Notification
    https://msdn.microsoft.com/en-us/library/ms743695(v=vs.110).aspx
    using System.ComponentModel;
    namespace SDKSample
    // This class implements INotifyPropertyChanged
    // to support one-way and two-way bindings
    // (such that the UI element updates when the source
    // has been changed dynamically)
    public class Person : INotifyPropertyChanged
    private string name;
    // Declare the event
    public event PropertyChangedEventHandler PropertyChanged;
    public Person()
    public Person(string value)
    this.name = value;
    public string PersonName
    get { return name; }
    set
    name = value;
    // Call OnPropertyChanged whenever the property is updated
    OnPropertyChanged("PersonName");
    // Create the OnPropertyChanged method to raise the event
    protected void OnPropertyChanged(string name)
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    handler(this, new PropertyChangedEventArgs(name));
    It is not so complex, you only need to refer to the interface from here:
    https://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx
    And understand that you have to do the following:
    For change notification to occur in a binding between a bound client and a data source, your bound type should either:
    Implement the INotifyPropertyChanged interface (preferred).
    Provide a change event for each property of the bound type
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • I cannot get a WindowsForms user control hosted in WPF/C# to show() PDF please help

    I have a WPF C# .NET 4.0. solution in VS2010 on Windows 7.   It contains a WPF hosting project and a WindowsFormsControl project where I've created a UserControl that should display an Acrobat CAcroAVDoc object from the Interop.Acrobat SDK com object (latest).
    The WPF Project contains this code to open a file which actually creates a new WindowsFormsUserControl (PDFViewerControl) that in turns opens the file, the UserControl is then added to a WindowsFormHost object in WPF main form.
    private void OpenFile(FileItem file)
    if (file.Extension.ToLower() == ".pdf")
      System.Windows.Forms.Integration.WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();
      WindowsFormsControls.PDFViewerControl viewer = new WindowsFormsControls.PDFViewerControl();
      viewer.Show();
      Boolean result = viewer.OpenFile(file.Path);
      if (!result)
       MessageBox.Show("Error opening document");
      host.Child = viewer;
      this.pdfViewWpf.Children.Add(host);
      viewer.Show();
    The PDFViewerControl OpenFile method contains this code and returns True when opening a PDF document via OpenInWindowEx.
    public Boolean OpenFile(String filename)
    CAcroAVDoc doc = Activator.CreateInstance(Type.GetTypeFromProgID("AcroExch.AVDoc")) as CAcroAVDoc;
    bool res = doc.OpenInWindowEx(filename, this.Handle.ToInt32(), 2, 1, 0, (short)Acrobat.PDViewMode.PDUseBookmarks, (short)Acrobat.AVZoomType.AVZoomFitWidth, 0, 0, 0);
    return res;
    Unfortunately though the PDF cannot be seen in WPF Host object.  If I place a LABEL on the windows forms user control, the label will show in WPF.  It seems the OpenInWindowEx is not loading a PDF object onto the user control.  Perhaps I need a resize method and event?
    I cannot locate any object on the PDFViewerControl user control that resembles a PDF document through debug.
    Any help/pointers much appreciated.
    this.Handle.ToInt32() does have a seemingly valid value (ie window handle).
    this.pdfViewWpf is a XAML <Grid>
    Dominic

    On further testing, I found the above code does actually work, BUT the HOST or the VIEWER or the DOC object disappear after the routine is finished.  I placed a label on the UserControl and noticed a flicker on the crseen draw which I capture on camtasia the result can be viewed here.  http://www.screencast.com/t/Z49gUTb3Xt
    Given the label is still around after the file open routine completes suggests the HOST and VIEWER objects are still exposed, just the DOC object resizes to zero height and width or just plain gone.
    Without the Label, same result.
    Any thoughts on how to retain the display of the CAcroAVDoc object would be much appreciated.

  • WPF Finding Selected ComboBox Item Within DataGrid

    Hi all... I'm having an issue trying to access the selected item value in a ComboBox within a DataGridTemplateColumn. 
    Through another question/answer I have got the ComboBox displaying the names as it should but the next step I'm having issues with is to be able to loop through each row in the DataGrid and determine the selected value of the ComboBox in that row as
    well as some other items and run some other code based on those values. 
    Any help would be appreciated. 
    Thanks,
    Greg
    <Grid>
    <DataGrid x:Name="gvDefaultCWWSchedule" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="10,109,10,214" AutoGenerateColumns="False" Grid.Row="0"
    AllowDrop="True" IsReadOnly="False" SelectionMode="Single" Background="Beige" CanUserAddRows="False">
    <DataGrid.Columns>
    <DataGridTemplateColumn Width="150">
    <DataGridTemplateColumn.CellTemplate>
    <DataTemplate>
    <ComboBox Name="ddlUsers"
    ItemsSource="{Binding Path=Users}"
    DisplayMemberPath="{Binding Name, Mode=TwoWay}"
    SelectedValuePath="{Binding Uid, Mode=TwoWay}"
    SelectedIndex="{Binding Uid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
    SelectionChanged="ComboBox_SelectionChanged"
    >
    <ComboBox.ItemTemplate>
    <DataTemplate>
    <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Name}" />
    </StackPanel>
    </DataTemplate>
    </ComboBox.ItemTemplate>
    </ComboBox>
    </DataTemplate>
    </DataGridTemplateColumn.CellTemplate>
    </DataGridTemplateColumn>
    <DataGridTextColumn Binding="{Binding WeekNumber}" />
    </DataGrid.Columns>
    </DataGrid>
    <Button Content="Button" HorizontalAlignment="Left" Margin="729,32,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
    public partial class Test : Window
    public Test()
    InitializeComponent();
    BindDefaultCWWSchedule();
    private void BindDefaultCWWSchedule()
    // THIS IS COMING FROM MY DB
    List<CurrentUser> UsersFinal = new List<CurrentUser>();
    UsersFinal.Add(new CurrentUser { Uid = 1, Name = "JOHN" });
    UsersFinal.Add(new CurrentUser { Uid = 2, Name = "BILL" });
    UsersFinal.Add(new CurrentUser { Uid = 3, Name = "MARY" });
    ObservableCollection<CWWDefaultScheduleWeek> DefaultSchedules = new ObservableCollection<CWWDefaultScheduleWeek>();
    DefaultSchedules.Add(new CWWDefaultScheduleWeek { Users = UsersFinal, WeekNumber = 1, SelectedUser = null });
    DefaultSchedules.Add(new CWWDefaultScheduleWeek { Users = UsersFinal, WeekNumber = 2, SelectedUser = null });
    DefaultSchedules.Add(new CWWDefaultScheduleWeek { Users = UsersFinal, WeekNumber = 3, SelectedUser = null });
    DefaultSchedules.Add(new CWWDefaultScheduleWeek { Users = UsersFinal, WeekNumber = 4, SelectedUser = null });
    gvDefaultCWWSchedule.ItemsSource = DefaultSchedules;
    private void Button_Click(object sender, RoutedEventArgs e)
    var rows = gvDefaultCWWSchedule.ItemsSource;
    ObservableCollection<CWWDefaultScheduleWeek> CWWSchedAssignments = new ObservableCollection<CWWDefaultScheduleWeek>();
    foreach (var row in rows)
    CWWDefaultScheduleWeek r = (CWWDefaultScheduleWeek)row;
    // FOR EACH ROW HERE I'M WANTING TO CREATE A LIST OF ITEMS AND RUN FURTHER CODE BASED ON IT... ISSUE IS FINDING THE ACTUAL SELECTED USER ON EACH ROW...
    CWWSchedAssignments.Add(new CWWDefaultScheduleWeek
    Users = r.Users,
    SelectedUser = r.SelectedUser,
    WeekNumber = r.WeekNumber
    private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    gvDefaultCWWSchedule.CommitEdit();
    public class CWWDefaultScheduleWeek
    public IEnumerable<CurrentUser> Users { get; set; }
    public CurrentUser SelectedUser { get; set; }
    public int WeekNumber { get; set; }
    public class CurrentUser
    public int Uid { get; set; }
    public string Name { get; set; }

    In a way, wpf is similar to web.
    More so than windows forms anyhow.
    XAML is mark up and flows like html.
    You have padding and margin which are rather familiar concepts.
    Whereas windows forms is absolute positioning and... well totally different from markup.
    You might find this sample interesting as a sort of mvvm taster.
    https://gallery.technet.microsoft.com/WPF-Dialler-simulator-d782db17
    and event handling equivalents
    http://social.technet.microsoft.com/wiki/contents/articles/30564.wpf-uneventful-mvvm.aspx
    Note
    With a combo you bind the selecteditem to a propfull and then you can put a method call in the setter.  That will then be invoked when the user changes selection.
    Good luck and welcome to wpf development.
    It's a great technology.
    Hope that helps.
    Recent Technet articles: Property List Editing;
    Dynamic XAML

  • How Do I Know What Element is Clicked in a WPF WebBrowser Control

    Hi,
    I am developing WPF Web browser based Application.
    In which if someone browse www.msdn.com and clicked on "Make a suggestion" button the I want to know the id of the button clicked and name of the url on which user will be redirected.
    Thanks.
    Pritesh

    WPF doesn't respond or subscribe to any kind of events that HTML elements within the web page may raise. The WebBrowser control is basically just a separate window that wraps an Internet Explorer within the WPF window and the web page that is displayed in
    the browser lives it own life inside this "box".
    You should handle these kind of things in the web page itself, for example using javascript.
    What you could from a WPF side of things is to add and invoke javascripts on the loaded web page. Please refer to the following thread for more information about this:
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/72f399b7-8c39-45f9-85ca-c683862c9b8c/prevent-the-selection-of-texts-webbrowser?forum=wpf
    If you have any questions about how to write the actual javascripts you should ask at
    http://forums.asp.net.
    Please remember to close your threads by marking all helpful posts as answer and please start a new thread if you have a new question.

  • Debugger exception on WPF loading

    Hello,
        I am looking for a little help with this.  I have a WPF browser form that I am trying to load.  I run the debugger, but when it gets to the page I get the following:
    An exception of type 'System.Security.SecurityException' occurred in System.Data.dll but was not handled in user code
    Additional information: Request for the permission of type 'System.Data.SqlClient.SqlClientPermission, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.
    If there is a handler for this exception, the program may be safely continued.
    The call stack for that shows this:
    > HomeInventoryWebForms.exe!HomeInventoryWebForms.frmMoviesAdd.dgMTVAddFormat_Window_Loaded(object sender, System.Windows.RoutedEventArgs e) Line 70 C#
    So here is the code behind the form:
    public frmMoviesAdd()
    InitializeComponent();
    this.Loaded += dgMTVAddFormat_Window_Loaded;
    this.Loaded += dgMTVAddGenre_Window_Loaded;
    private void dgMTVAddFormat_Window_Loaded(object sender, RoutedEventArgs e)
    FormatDataClassesDataContext data = new FormatDataClassesDataContext();
    List<tblFormat> Format = (from FormatName in data.tblFormats select FormatName).ToList();
    dgMTVAddFormat.ItemsSource = Format;
    This is backed up with LINQ to SQL class that was auto generated:
    [global::System.Data.Linq.Mapping.DatabaseAttribute(Name="HomeInventory")]
    public partial class FormatDataClassesDataContext : System.Data.Linq.DataContext
    private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
    #region Extensibility Method Definitions
    partial void OnCreated();
    partial void InserttblFormat(tblFormat instance);
    partial void UpdatetblFormat(tblFormat instance);
    partial void DeletetblFormat(tblFormat instance);
    #endregion
    public FormatDataClassesDataContext() :
    base(global::HomeInventoryWebForms.Properties.Settings.Default.HomeInventoryConnectionString, mappingSource)
    OnCreated();
    public FormatDataClassesDataContext(string connection) :
    base(connection, mappingSource)
    OnCreated();
    public FormatDataClassesDataContext(System.Data.IDbConnection connection) :
    base(connection, mappingSource)
    OnCreated();
    public FormatDataClassesDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
    base(connection, mappingSource)
    OnCreated();
    public FormatDataClassesDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
    base(connection, mappingSource)
    OnCreated();
    public System.Data.Linq.Table<tblFormat> tblFormats
    get
    return this.GetTable<tblFormat>();
    [global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.tblFormat")]
    public partial class tblFormat : INotifyPropertyChanging, INotifyPropertyChanged
    private static PropertyChangingEventArgs emptyChangingEventArgs = new PropertyChangingEventArgs(String.Empty);
    private int _FormatID;
    private string _FormatName;
    #region Extensibility Method Definitions
    partial void OnLoaded();
    partial void OnValidate(System.Data.Linq.ChangeAction action);
    partial void OnCreated();
    partial void OnFormatIDChanging(int value);
    partial void OnFormatIDChanged();
    partial void OnFormatNameChanging(string value);
    partial void OnFormatNameChanged();
    #endregion
    public tblFormat()
    OnCreated();
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FormatID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
    public int FormatID
    get
    return this._FormatID;
    set
    if ((this._FormatID != value))
    this.OnFormatIDChanging(value);
    this.SendPropertyChanging();
    this._FormatID = value;
    this.SendPropertyChanged("FormatID");
    this.OnFormatIDChanged();
    [global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_FormatName", DbType="VarChar(MAX) NOT NULL", CanBeNull=false)]
    public string FormatName
    get
    return this._FormatName;
    set
    if ((this._FormatName != value))
    this.OnFormatNameChanging(value);
    this.SendPropertyChanging();
    this._FormatName = value;
    this.SendPropertyChanged("FormatName");
    this.OnFormatNameChanged();
    public event PropertyChangingEventHandler PropertyChanging;
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void SendPropertyChanging()
    if ((this.PropertyChanging != null))
    this.PropertyChanging(this, emptyChangingEventArgs);
    protected virtual void SendPropertyChanged(String propertyName)
    if ((this.PropertyChanged != null))
    this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    #pragma warning restore 1591
    Now I am trying to bind this all to a checked box datagrid in the WPF with code that looks like this:
    <Label x:Name="lblMTVAddFormat" Style="{StaticResource Label Style}" Content="Formats" Margin="335,74,0,0" Width="97"/>
    <DataGrid x:Name="dgMTVAddFormat" Margin="437,74,10,265" AutoGenerateColumns="False">
    <DataGrid.Columns>
    <DataGridCheckBoxColumn Binding="{Binding fBool}" />
    <DataGridTextColumn Binding="{Binding Path='FormatName'}" />
    </DataGrid.Columns>
    </DataGrid>
    This is all running from a local disk, connected to a remote developer database.  I have no build errors or anything when I go to the debug, hitting continue sends it to another break for the exact same reason.  Which loops out of the program and
    shuts down the debugger.  Could anyone point me in the direction to go since it is throwing this error on debug? 
    Michael R. Mastro II

    The error message should be pretty self-explanatory; your application is not permitted to access to the database due to security reasons.
    You must deploy your application as a full trust application for it to be able to to this. Please refer to the following two links for more information about how to do this:
    How to run WPF – XBAP as Full Trust Application:
    http://blogs.microsoft.co.il/maxim/2008/03/05/how-to-run-wpf-xbap-as-full-trust-application/
    http://stackoverflow.com/questions/5212973/request-for-the-permission-of-type-system-data-sqlclient-sqlclientpermission-s
    And please refer to MSDN for more information about XBAP security considerations:
    https://msdn.microsoft.com/en-us/library/aa970060(v=vs.110).aspx#xbap_security_considerations
    Please also rememember to close your threads by marking helpful posts as answer and then start a new thread if you have new question.

  • Create a Behavior for Calendar in a WPF UserControl to Select and Unselect dates with one click

    Hi to everyone,
    I am developing an application with a WPF Client. This Client use the MVVM pattern.
    In an UserControl the application must show some Calendars, so the user can select one or multiple dates.
    For that use, I should implement some behavior that allows the user click once in a date and that date is selected (what already exists in .NET Framework) and with another click in the same date, that date is now unselected.
    I've already made some searches and can't find anything useful.
    This kind of behavior it is possible to implement in the Calendar Control? How exactly I do this?
    Thanks for reading/helping
    Rafael Duarte

    You should be able to accomplish this by modifying the default template of the CalendarDayButtonStyle of the Calendar and handling the PreviewMouseLeftButtonDown of the Grid in the default template. Here is an example:
    <Window.Resources>
    <Style x:Key="CalendarDayButtonStyle1" TargetType="{x:Type CalendarDayButton}">
    <Setter Property="MinWidth" Value="5"/>
    <Setter Property="MinHeight" Value="5"/>
    <Setter Property="FontSize" Value="10"/>
    <Setter Property="HorizontalContentAlignment" Value="Center"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Template">
    <Setter.Value>
    <ControlTemplate TargetType="{x:Type CalendarDayButton}">
    <Grid Background="Transparent" PreviewMouseLeftButtonDown="Grid_PreviewMouseLeftButtonDown">
    <VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="CommonStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0:0:0.1"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="Normal"/>
    <VisualState x:Name="MouseOver">
    <Storyboard>
    <DoubleAnimation Duration="0" To="0.5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="HighlightBackground"/>
    </Storyboard>
    </VisualState>
    <VisualState x:Name="Pressed">
    <Storyboard>
    <DoubleAnimation Duration="0" To="0.5" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="HighlightBackground"/>
    </Storyboard>
    </VisualState>
    <VisualState x:Name="Disabled">
    <Storyboard>
    <DoubleAnimation Duration="0" To="0" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="HighlightBackground"/>
    <DoubleAnimation Duration="0" To=".35" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="NormalText"/>
    </Storyboard>
    </VisualState>
    </VisualStateGroup>
    <VisualStateGroup x:Name="SelectionStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="Unselected"/>
    <VisualState x:Name="Selected">
    <Storyboard>
    <DoubleAnimation Duration="0" To=".75" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="SelectedBackground"/>
    </Storyboard>
    </VisualState>
    </VisualStateGroup>
    <VisualStateGroup x:Name="CalendarButtonFocusStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <!--<VisualState x:Name="CalendarButtonFocused">
    <Storyboard>
    <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="DayButtonFocusVisual">
    <DiscreteObjectKeyFrame KeyTime="0">
    <DiscreteObjectKeyFrame.Value>
    <Visibility>Visible</Visibility>
    </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    </Storyboard>
    </VisualState>-->
    <!-- <VisualState x:Name="CalendarButtonUnfocused">
    <Storyboard>
    <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetProperty="Visibility" Storyboard.TargetName="DayButtonFocusVisual">
    <DiscreteObjectKeyFrame KeyTime="0">
    <DiscreteObjectKeyFrame.Value>
    <Visibility>Collapsed</Visibility>
    </DiscreteObjectKeyFrame.Value>
    </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames>
    </Storyboard>
    </VisualState>-->
    </VisualStateGroup>
    <VisualStateGroup x:Name="ActiveStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="Active"/>
    <VisualState x:Name="Inactive">
    <Storyboard>
    <ColorAnimation Duration="0" To="#FF777777" Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="NormalText"/>
    </Storyboard>
    </VisualState>
    </VisualStateGroup>
    <VisualStateGroup x:Name="DayStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="RegularDay"/>
    <VisualState x:Name="Today">
    <Storyboard>
    <DoubleAnimation Duration="0" To="1" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="TodayBackground"/>
    <ColorAnimation Duration="0" To="#FFFFFFFF" Storyboard.TargetProperty="(TextElement.Foreground).(SolidColorBrush.Color)" Storyboard.TargetName="NormalText"/>
    </Storyboard>
    </VisualState>
    </VisualStateGroup>
    <VisualStateGroup x:Name="BlackoutDayStates">
    <VisualStateGroup.Transitions>
    <VisualTransition GeneratedDuration="0"/>
    </VisualStateGroup.Transitions>
    <VisualState x:Name="NormalDay"/>
    <VisualState x:Name="BlackoutDay">
    <Storyboard>
    <DoubleAnimation Duration="0" To=".2" Storyboard.TargetProperty="Opacity" Storyboard.TargetName="Blackout"/>
    </Storyboard>
    </VisualState>
    </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <Rectangle x:Name="TodayBackground" Fill="#FFAAAAAA" Opacity="0" RadiusY="1" RadiusX="1"/>
    <Rectangle x:Name="SelectedBackground" Fill="#FFBADDE9" Opacity="0" RadiusY="1" RadiusX="1"/>
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}"/>
    <Rectangle x:Name="HighlightBackground" Fill="#FFBADDE9" Opacity="0" RadiusY="1" RadiusX="1"/>
    <ContentPresenter x:Name="NormalText" TextElement.Foreground="#FF333333" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="5,1,5,1" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    <Path x:Name="Blackout" Data="M8.1772461,11.029181 L10.433105,11.029181 L11.700684,12.801641 L12.973633,11.029181 L15.191895,11.029181 L12.844727,13.999395 L15.21875,17.060919 L12.962891,17.060919 L11.673828,15.256231 L10.352539,17.060919 L8.1396484,17.060919 L10.519043,14.042364 z" Fill="#FF000000" HorizontalAlignment="Stretch" Margin="3" Opacity="0" RenderTransformOrigin="0.5,0.5" Stretch="Fill" VerticalAlignment="Stretch"/>
    <Rectangle x:Name="DayButtonFocusVisual" IsHitTestVisible="false" RadiusY="1" RadiusX="1" Stroke="#FF45D6FA" Visibility="Collapsed"/>
    </Grid>
    <ControlTemplate.Triggers>
    <MultiTrigger>
    <MultiTrigger.Conditions>
    <Condition Property="IsSelected" Value="True"/>
    <Condition Property="IsFocused" Value="True"/>
    </MultiTrigger.Conditions>
    <Setter Property="Visibility" TargetName="DayButtonFocusVisual" Value="Visible"/>
    </MultiTrigger>
    </ControlTemplate.Triggers>
    </ControlTemplate>
    </Setter.Value>
    </Setter>
    </Style>
    </Window.Resources>
    <Calendar x:Name="cal" CalendarDayButtonStyle="{DynamicResource CalendarDayButtonStyle1}" />
    private void Grid_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
    Grid grid = sender as Grid;
    CalendarDayButton button = FindParent<CalendarDayButton>(grid);
    if (button.IsSelected) {
    Calendar cal = FindParent<Calendar>(button);
    if (cal.SelectedDate.HasValue) {
    cal.SelectedDates.Remove(cal.SelectedDate.Value);
    e.Handled = true;
    Hope that helps.
    Please remember to mark helpful posts as answer and/or helpful.

Maybe you are looking for

  • Export Data Source Transport Problem

    Hi All, I have IO FI Super Number - did export data source for that and generated 8zfssupno for myself BW system in Dev system. Used that export DS for another MD Account and created transfer rule. Now when i try to transport the Request to QA env. t

  • Restoring iPhone 6 from iPhone 5s backup

    Hello, I have a major problem with my iPhone 6. Until today i had a 5s. Last full backed up a few days ago. Today, my father wanted to swap his 6 with my 5s because he can't use it. I connected his 6 to my mac and he started to sync (the iPhone 6 was

  • File Type and Size for Video iPod

    I have the latest ipod that does it all, but I am a little concerned about the lack of control on the file type size. I can export a mp4 file with my own settings so it isn't such a large file but it won't load or play. I can convert the file but it

  • Restrictive pdf control plug-in?

    Hello Is there a plug-in for acrobat that restricts the manipulation of 3D models? I want to provide a 3D model that can be viewed from all angles, but nothing else.

  • Is it possible to give a choice to user to connect any one server on a network.

    Dear Forum members, I have three servers windows 2008 r2 in my network but each server has its own set of users. a user member of one server cant' login to other with the same credentials.  Secondly PC at a time is part of one domain. every time I ha