Posts in the 'WPF' category

Feb
7
2010

Watermarked TextBox with an AttachedProperty



Posted in Programming and WPF

Ever wanted to create a watermark effect for a TextBox in WPF? Most of the tutorials scattered around have either used static text or created a subclass of TextBox. I wanted to use an AttachedProperty instead, and though it took a while to try every possible combination of brackets and bindings I came up with the following to create an AttachedProperty which you can apply in any ResourceDictionary or wherever you keep your Styles.


Watermarks with Attached Properties
Get the code after the jump.

Read more »

Dec
19
2009

Minimize To Tray with WPF



Posted in Programming and WPF

I’ve been working on porting LockCrypt to WPF from Java and was pretty shocked to find there was no no built-in support. It’s entirely possible, but you have to use WinForms. I based this on Delay‘s sample, feel free to use it however you wish.

namespace Lime49.WPF {
    /// <summary>
    /// Tray minimization utility, based on Delay's code - http://blogs.msdn.com/delay/.
    /// </summary>
    public static class TrayMinimizer {
        /// <summary>
        /// Enables "minimize to tray" behavior for the specified Window.
        /// </summary>
        /// <param name="window">Window to enable the behavior for.</param>
        public static void EnableMinimizeToTray(Window window) {
            if(MinimizeInstances.ContainsKey(window)) {
                Console.WriteLine(string.Format("Minimization already enabled for '{0}'", window.Title));
            } else {
                var instance = new MinimizeToTrayInstance(window);
                instance.Enable();
                MinimizeInstances.Add(window, instance);
            }
        }

Read more »

Sep
7
2009

WPF: TextBox Error Notification Through Style



Posted in Programming and WPF

By default, WPF doesn’t provide any visual indication when ValidationRules aren’t met for TextBoxes. When I was learning WPF, I read a post about providing error notification for TextBoxes through the user of a style. I can’t find the article/post, but it never worked properly for me so I’ve modified and fixed what I had. This only works if there are ValidationRules bound to the TextBox, and it only displays the first failed rule.

<style TargetType="{x:Type TextBoxBase}" x:Key="{x:Type TextBox}">
  <setter Property="Margin" Value="2" />
  <setter Property="SnapsToDevicePixels" Value="True"/>
  <setter Property="OverridesDefaultStyle" Value="false"/>
  <setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
  <setter Property="FocusVisualStyle" Value="{x:Null}"/>
  <setter Property="MinWidth" Value="80"/>
  <setter Property="MinHeight" Value="20"/>
  <setter Property="AllowDrop" Value="true"/>
  <setter Property="Background" Value="{StaticResource WindowBackgroundBrush}" />
  <setter Property="BorderBrush" Value="{StaticResource SolidBorderBrush}" />
  <setter Property="Template">
...
</setter></style>

The rest is after the jump.

Read more »

Jul
31
2009

WPF: Changing Input Focus to Hidden Elements



Posted in Programming and WPF

When trying to change the focused element in the WPF recipe management app I develop, ChickenPing, I recently ran into a problem. I wanted a shortcut key (Ctrl + something) to change the selected tab in a TabControl, then focus an element in that tab. There are a few ways you might try doing this, both do more or less the same thing and both will fail unless the tab in question is already selected. For example:

 tabControl.SelectedItem = someTab;
 someTextBox.Focus();
 FocusManager.SetFocusedElement(this, someTextBox);
 // both only work unless the tab which contains them is visible.

The problem is that an element can only be focused if it is visible. Making the item visible just before trying to focus it fails because the change hasn’t had time to take effect.

Read more »

Jul
29
2009

TopMost Window In XAML



Posted in Programming and WPF

I was kind of looking forward to delving into some native call to make a Window always on top in WPF, but it was actually surprisingly easy, a single binding in the Window’s declaration:

<Window ...
	Topmost="{Binding ElementName=itmTopMost,Path=IsChecked}"
...
	<MenuItem Header="_Always on Top" x:Name="itmTopMost" IsCheckable="True" />

No code involved!

Jun
13
2009

Editable ComboBox with XCeed DataGrid



Posted in Programming and WPF

I’ve recently started using XCeed’s DataGrid for WPF instead of he WPF toolkit DataGrid because overall it seems to have more features. One of the problems which I couldn’t find any reference to was using editable comboboxes when editing an item. I’m using an ObjectDataProvider as the ItemsSource for a ComboBox, but I wanted to let a user type a value as well as select one from the list.

The solution I eventually used lets a user add an item to the list of items which can then be selected when editing other items in the DataGrid.

Once you’ve declared the ObjectDataProvider in XAML, you need a CellEditor template for the column which will use the ComboBox (code below).

<xcdg:column .CellEditor>
    <xcdg:celleditor>
        </xcdg:celleditor><xcdg:celleditor .EditTemplate>
            <datatemplate>
                <combobox x:Name="cboMeasurement" IsVisibleChanged="cbo_IsVisibleChanged"
                      ItemsSource="{Binding Collection,Source={StaticResource measurementProvider}}" SelectedValue="{xcdg:CellEditorBinding}" IsEditable="True" Foreground="Black" IsSynchronizedWithCurrentItem="True" />
            </datatemplate>
        </xcdg:celleditor>
 
</xcdg:column>

Read more »

May
1
2009

WPF: DataGrid And The Return Key



Posted in Programming and WPF

A decent DataGrid is really the only thing WPF doesn’t have. The WPF Toolkit DataGrid is a great addition but it’s still lacking in a few places.

To me, it would seem natural for the Tab key to move to the next column and Enter to move to the next row, but there isn’t really support for this.

After experimenting with KeyUp and KeyDown events, I came up with the following method, based on a similar technique by Vincent Sibal. It makes the DataGrid more usable in my opinion.

Read more »

Apr
27
2009

C#: AutoSave with WPF



Posted in Programming and WPF

Creating an automatic save for ResourceBlender Express was actually a lot easier than I thought it would be but I’ll post the source here for anyone else wondering how to do it.

My .xaml.cs file has four class variables to make it work, and the save method executes in a separate thread to prevent it locking the UI during saving (actually a BackgroundWorker).

BackgroundWorker worker;
DispatcherTimer timer;
int autoSaveInterval = 3000;
DateTime lastSave;

The DispatcherTimer times the save at a specified interval and the BackgroundWorker executes the operation. In the class constructor I setup the DispatchTimer:

Read more »

Mar
11
2009

WPF: GridView Column Width Calculator



Posted in Programming and WPF

The GridView in WPF isn’t bad, but is pretty basic compared to the one in ASP.NET. There’s isn’t really a decent method for setting column width, so I wrote this converter to calculate the width needed to fill the parent ListView.

If you call it with no parameters, it’ll take up the remaining width in the ListView:

// fills remaining width in the ListView
<gridviewcolumn Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListView}},Converter={StaticResource WidthConverter}}">
</gridviewcolumn>

If you use an integer as a parameter, the value will act as the minimum width

// fills remaining width in the ListView, unless the remaining width is less than the parameter
<gridviewcolumn Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListView}},Converter={StaticResource WidthConverter},ConverterParameter=200}">
</gridviewcolumn>

Or, you can specify a GridView type width with an asterisk, and the percentage width of the ListView will be returned

// calculates 30% of the ListView width
<gridviewcolumn Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListView}},Converter={StaticResource WidthConverter},ConverterParameter=0.3*}">
</gridviewcolumn>

Read more »