//http://simpledbbrowser.codeplex.com/
//License: Microsoft Public License (Ms-PL)
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace AWS.Framework.WPF.Utility
{
public sealed class Helpers
{
#region Constructor
private Helpers()
{ }
#endregion // Constructor
#region Methods
public static void UpdateFocusedField()
{
FrameworkElement fwe = Keyboard.FocusedElement as FrameworkElement;
if (fwe != null)
{
BindingExpression expression = null;
if (fwe is TextBox)
expression = fwe.GetBindingExpression(TextBox.TextProperty);
// TODO - developers - add more control types here. Won't be that many.
// this would include custom TextBox controls or 3rd party TextBox controls
if (expression != null)
expression.UpdateSource();
}
}
#endregion // Methods
}
}
Month: February 2011
Find Visual Child
//http://simpledbbrowser.codeplex.com/
//License: Microsoft Public License (Ms-PL)
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace AWS.Framework.WPF.Utility
{
public sealed class Helpers
{
public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
{
for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(obj, i);
if (child != null && child is childItem)
return (childItem)child;
else
{
childItem childOfChild = FindVisualChild<childItem>(child);
if (childOfChild != null)
return childOfChild;
}
}
return null;
}
}
}
The UniformGrid
<Window x:Class="LayoutPanels.TheUniformGrid"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TheUniformGrid" Height="300" Width="300">
<UniformGrid Rows="2" Columns="2">
<Button>Top Left</Button>
<Button>Top Right</Button>
<Button>Bottom Left</Button>
<Button>Bottom Right</Button>
</UniformGrid>
</Window>
Implement validation logic on custom objects and then bind to them(Mouse-over to see the validation error message).
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF IDataErrorInfo Sample" Width="350" Height="150"
xmlns:src="clr-namespace:WpfApplication1">
<Window.Resources>
<src:Employee x:Key="data"/>
<Style x:Key="textBoxInError" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<StackPanel Margin="20">
<TextBox Style="{StaticResource textBoxInError}">
<TextBox.Text>
<Binding Path="Age" Source="{StaticResource data}"
ValidatesOnExceptions="True"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataErrorValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
public class Employee : IDataErrorInfo
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public string Error
{
get
{
return null;
}
}
public string this[string name]
{
get
{
string result = null;
if (name == "Age")
{
if (this.age < 0 || this.age > 50)
{
result = "Age must not be less than 0 or greater than 50.";
}
}
return result;
}
}
}
}
IValueConverter and ValidationRule
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:WpfApplication1"
Title="Random Numbers Built to Order">
<Window.Resources>
<ObjectDataProvider x:Key="nextRandomNumber" ObjectType="{x:Type sys:Random}" MethodName="Next">
<ObjectDataProvider.MethodParameters>
<sys:Int32>0</sys:Int32>
<sys:Int32>10</sys:Int32>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<local:StringToInt32Converter x:Key="numConverter" />
</Window.Resources>
<StackPanel DataContext="{StaticResource nextRandomNumber}">
<Label>Min</Label>
<TextBox Name="minTextBox" ToolTip="{Binding ElementName=minTextBox, Path=(Validation.Errors)[0].ErrorContent}">
<TextBox.Text>
<Binding Path="MethodParameters[0]" BindsDirectlyToSource="True" Converter="{StaticResource numConverter}">
<Binding.ValidationRules>
<local:IntegerValidator />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Label>Max</Label>
<TextBox Name="maxTextBox" ToolTip="{Binding ElementName=maxTextBox, Path=(Validation.Errors)[0].ErrorContent}">
<TextBox.Text>
<Binding Path="MethodParameters[1]" BindsDirectlyToSource="True" Converter="{StaticResource numConverter}">
<Binding.ValidationRules>
<local:IntegerValidator />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<Label>Random</Label>
<TextBox Text="{Binding Mode=OneTime}" IsReadOnly="True" />
<Button Name="nextButton">Next</Button>
</StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace WpfApplication1 {
public partial class Window1 : System.Windows.Window {
public Window1() {
InitializeComponent();
nextButton.Click += new RoutedEventHandler(nextButton_Click);
}
void nextButton_Click(object sender, RoutedEventArgs e) {
((ObjectDataProvider)Resources["nextRandomNumber"]).Refresh();
}
}
public class StringToInt32Converter : IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return ((int)value).ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return int.Parse((string)value);
}
}
public class IntegerValidator : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
try {
int.Parse((string)value);
return ValidationResult.ValidResult;
}
catch( Exception ex ) {
return new ValidationResult(false, ex.Message);
}
}
}
}
Specify Validation Rules for a Binding
//File:Window.xaml.cs
using System.Globalization;
using System.Windows.Controls;
namespace WpfApplication1
{
public class PercentageRule : ValidationRule
{
public override ValidationResult Validate(object value,CultureInfo cultureInfo)
{
string stringValue = value as string;
if(!string.IsNullOrEmpty(stringValue))
{
double doubleValue;
if(double.TryParse(stringValue, out doubleValue))
{
if(doubleValue >= 0 && doubleValue <= 100)
{
return new ValidationResult(true, null);
}
}
}
return new ValidationResult(false, "Must be a number between 0 and 100");
}
}
}
[/csharp]
Rotate
<Window x:Class="Workspace.DockExample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Workspace" Width="640" Height="480">
<Canvas Height="200" Width="200">
<Polyline Points="25,25 0,50 25,75 50,50 25,25 25,0" Stroke="Blue" StrokeThickness="10"
Canvas.Left="75" Canvas.Top="50">
<Polyline.RenderTransform>
<RotateTransform CenterX="25" CenterY="50" Angle="45" />
</Polyline.RenderTransform>
</Polyline>
<Polyline Points="25,25 0,50 25,75 50,50 25,25 25,0" Stroke="Blue" StrokeThickness="10"
Opacity="0.25" Canvas.Left="75" Canvas.Top="50" />
</Canvas>
</Window>

