Thursday, November 1, 2007

Remove control box of Paged WPF applications

  • Get the instance of the current Window from Application.Current and remove it's Control box by setting WindowStyle=None.

    public partial class Page1 : System.Windows.Controls.Page
    {
    public Page1()
    {

    this.Loaded += new RoutedEventHandler(Page1_Loaded);
    InitializeComponent();
    }

    void Page1_Loaded(object sender, RoutedEventArgs e)
    {
    Application.Current.MainWindow.WindowStyle = WindowStyle.None;
    }

    }

    Application.Current.MainWindow will be initialized only in Loaded event of Page

  • <Application.Resources>
    <Style TargetType ="{x:Type NavigationWindow}">
    <Setter Property ="WindowStyle" Value="None"/>
    </Style>
    </Application.Resources>

Wednesday, October 17, 2007

An extented VisualTreeHelper class

Usually if we want to get immediate parent of a Visual(Which considers the elements in Template also) we could use the VisualTreeHelper.GetParent method.This works easy for parent.
But think of getting the children of Visual..Its difficult to call VisualTreeHelper.GetChildren because this needs the index of child.
Here comes the role of this class which wraps these methods and makes its usage simple.

Code

public static class VisualTreeHelperEx
{
public static T FindVisualAncestorByType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T parent = default(T);
parent = FindVisualAncestorByType<T>(VisualTreeHelper.GetParent(dependencyObject));
return parent;
}
public static T FindVisualChildByType<T>(DependencyObject dependencyObject) where T : DependencyObject
{
if (dependencyObject == null) return default(T);
if (dependencyObject is T) return (T)dependencyObject;
T child = default(T);
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
child = FindVisualChildByType<T>(VisualTreeHelper.GetChild(dependencyObject, i));
if (child != null) return child;
}
return null;
}
}

Usage


Window W = VisualTreeHelperEx.FindVisualAncestorByType <Window>(grd);
Rectangle r= VisualTreeHelperEx.FindVisualChildByType<Rectangle>(grd)