C# & WPF Notes

1) WPF: Window vs Page vs UserControl

  • Window is used when creating dialog based applications
  • Page is used when creating navigation based applications
  • UserControl is a reusable user-created component which can be used in multiple windows in any type of application

2) WPF: Change Start up Window

Change App.xaml -> <Application.StartupUri>

3) WPF: Aligning the base line of a Label and its TextBox

Let’s say I have a simple TextBox next to a Label:

<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label Margin="3">MyLabel</Label>
        <TextBox Margin="3" Width="100">MyText</TextBox>
    </StackPanel>
    ...
</StackPanel>

This yields the following result:

As you can see, the base lines of MyLabel and MyText are not aligned, which looks ugly.

This behaviour is caused by the fact that the TextBox defaults to a vertical alignment of Stretch, which causes it to fill the available space and have the extra couple of pixels under the text. Use this instead:

<StackPanel>
    <StackPanel Orientation="Horizontal">
        <Label >MyLabel</Label>
        <TextBox VerticalAlignment="Center" Width="100">MyText</TextBox>
    </StackPanel>
</StackPanel>

which yields:

Get Windows user’s Documents Path

You should use Environment.GetFolderPath() for getting environment folders. In particular, use Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), which will give you the “My Documents” folder for the user that the application is running under.

For more Special Folders, refer to: Environment.SpecialFolder Enum

4) C#: Saving a file and automatically create directories

Use new FileInfo(path).Directory.Create()

This creates anything in the hierarchy that’s required. If the directory already exists it does nothing.

5) WPF: Run as Administrator

  • Right click on your WPF project -> Add File
  • Select Manifest File & name it app.manifest
  • Change the requestedExecutionLevel from asInvoker to requireAdministrator
  • Open the properties of your Project -> Application Tab -> Select the manifest file created above

6) C#: Repeat a character n times

 string tabs = new String('\t', n); 

(to be continued…)