Nifty time savers for WPF development
I just published an article on Code Project, that explains how to use my latest FM USB library for building real world software radio receiver with WPF. There I referenced to some nifty WPF time savers, I’m using for everyday development. So, today I want to share those code pieces with you.
Binding time savers
Want to use following syntax for set binding in code?
Presets.SetBinding(ListBox.ItemsSourceProperty, _device, "Presets");
This piece of code sets binding to Preset DependencyObject, which is Listbox and connects ListBox.ItemsSource dependency property with “Presets” property of CLR object _device. How it done? Simple, as usual
[DebuggerStepThrough]
public static BindingExpressionBase SetBinding(this DependencyObject target, DependencyProperty dp, object source, string path) {
Binding b = new Binding(path);
b.Source = source;
return BindingOperations.SetBinding(target, dp, b);
}
But what to do when we need a converter? Simple:
[DebuggerStepThrough]
public static BindingExpressionBase SetBinding(this DependencyObject target, DependencyProperty dp, object source, string path, IValueConverter converter) {
Binding b = new Binding(path);
b.Source = source;
b.Converter = converter;
return BindingOperations.SetBinding(target, dp, b);
}
However to use this method, we need to create special object, which implements IValueConverter. Whey not to do it generically? Like this:
SignalTransform.SetBinding(ScaleTransform.ScaleYProperty, _device.RDS,"SignalStrength", new ValueConverter<byte, double>(b => { return 1-(b / 36d); }));
But we need this special handy ValueConverter class. What’s the problem? Here come the king:
public class ValueConverter<TIN, TOUT> : IValueConverter {
public ValueConverter(Func<TIN, TOUT> forwardConversion) {
ForwardConversion = forwardConversion;
}public ValueConverter(Func<TIN, TOUT> forwardConversion, Func<TOUT, TIN> reverseConversion) {
ForwardConversion = forwardConversion;
ReverseConversion = reverseConversion;
}public Func<TIN, TOUT> ForwardConversion { get; set; }
public Func<TOUT, TIN> ReverseConversion { get; set; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
try {
var in1 = Object.ReferenceEquals(value, DependencyProperty.UnsetValue) ? default(TIN) : (TIN)value;
return ForwardConversion(in1);
} catch {
return Binding.DoNothing;
}
}public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
try {
var out1 = Object.ReferenceEquals(value, DependencyProperty.UnsetValue) ? default(TOUT) : (TOUT)value;
return ReverseConversion(out1);
} catch {
return Binding.DoNothing;
}
}}
Isn’t it really simple? But what to do with ugly App.Current.Dispatcher.BeginInvoke((SendOrPostCallback)delegate(object o)…? Use dispatcher time savers.
Dispatcher time savers
Don’t you ever want to do this in order to make context switching between UI thread and other application thread in WPF?
this.Dispatch(() => {… DO SOMETHING IN UI THREAD …};
Now you can (with default and preset DispatcherPriority:
public static DispatcherOperation Dispatch(this DispatcherObject sender, Action callback) { return sender.Dispatch(DispatcherPriority.Normal, callback); }
public static DispatcherOperation Dispatch(this DispatcherObject sender, DispatcherPriority priority, Action callback) {
if (sender.Dispatcher == null) return null;
if (sender.Dispatcher.CheckAccess()) {
callback();
return null;
} else {
return sender.Dispatcher.BeginInvoke(priority, callback);
}
}
Nice, isn’t it? But what to do if we do not want to set binding, but we do want to be notified about property change of dependency objects?
Bindingless handlers time saver
Let’s assume, that we have “Tune” UIelement, which has Angle property, but not exposes PropertyChanged event (like it done with Rotary custom control by Expression Blend team… Designers, you know…
However I want to be able to add handler for Angle dependency property changed event and do something when it changed. Like this:
Tune.AddValueChanged(RotaryControl.RotaryControl.AngleProperty, (s, ex) => {
_device.Tune(Tune.Angle > _prevTune);
_prevTune = Tune.Angle;
});
Here comes our time saver for this purpose:
public static void AddValueChanged(this DependencyObject sender, DependencyProperty property, EventHandler handler) {
DependencyPropertyDescriptor.FromProperty(property, sender.GetType()).AddValueChanged(sender, handler);
}
But if we add handler we should be able to remove it too.
public static void RemoveValueChanged(this DependencyObject sender, DependencyProperty property, EventHandler handler) {
DependencyPropertyDescriptor.FromProperty(property, sender.GetType()).RemoveValueChanged(sender, handler);
}
Now we done with some of my nifty helpers. And last, but not the least:
All times question: how to scale ranges
Here is how
public static double ToRange(this double value, double minSource, double maxSource, double minTarget, double maxTarget) {
var sr = maxSource – minSource;
var tr = maxTarget – minTarget;
var ratio = sr / tr;
return minTarget+(value / ratio);
}
Now we can connect them and get something like this:
Volume.AddValueChanged(RotaryControl.RotaryControl.AngleProperty, (s, ex) => {
DirectSoundMethods.Volume = (int)Volume.Angle.ToRange(Volume.CounterClockwiseMostAngle, Volume.ClockwiseMostAngle, -4000, 0);
});
Isn’t it brilliant?
Have a good day and be sure to read and rate my last article on Code Project
Be good people.
You may also be interested with:
- Real singleton approach in WPF application
- INotifyPropertyChanged auto wiring or how to get rid of redundant code
January 8th, 2009 · Comments (2)
2 Responses to “Nifty time savers for WPF development”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard




January 8th, 2009 at 11:55 am
Dispatcher.Invoke has an overload that takes a simple delegate, as of SP1.
The SetBinding stuff isn’t that much of an improvement over using object initialization syntax, but that’s just an opinion.
Otherwise, nice stuff.
January 18th, 2009 at 10:28 am
[...] also added a few other articles and examples where he uses his FM Radio to demonstrate some useful XAML Time Savers. I can see a nice potential collaboration between Tamir and Jay Smith of [...]