Search This Blog

Monday, November 4, 2013

ControlTemplate WPF Example

WPF > Controls  > Templates > ControlTemplate

ControlTemplate defines the visual elements tree that is applied as the control template for a control.
ContentPresenter it is a placeholder for any XAML content and it can be used to insert content at runtime.

Example: Create Ellipse Button

<Window x:Class="WPF_Tutorial.MainWindow"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1">

    <Window.Resources>
        <ControlTemplate TargetType="Button" x:Key="ctButton" >
            <Grid>
                <Ellipse Fill="{ TemplateBinding Background }" Height="{TemplateBinding Height }">
                </Ellipse>
                <ContentPresenter VerticalAlignment="Center" HorizontalAlignment="Center" Content="{TemplateBinding Button.Content}" />
            </Grid>
        </ControlTemplate>
    </Window.Resources>

    <Grid>
        <Button Content="Ellipse Button" HorizontalAlignment="Left" VerticalAlignment="Top"
                Background="BlueViolet"
                Width="100" Height="100" Template="{ StaticResource ctButton}" Foreground="#FFF3E2E2">
        </Button>
    </Grid>
</Window>

Friday, November 1, 2013

Disable Script Errors WebBrowser WPF

WPF > Controls  > WebBrowser > Disable Script Errors

WebBrowser WPF control doesn't have property to disable script errors.
Using reflection we can solve this problem.

Solution:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
   wb1.Navigated += new NavigatedEventHandler(WebBrowser_Navigated);
}

void WebBrowser_Navigated(object sender, NavigationEventArgs e)
{
   HideJsScriptErrors((WebBrowser) sender);
}

public void HideJsScriptErrors(WebBrowser wb)
{
   // IWebBrowser2 interface
   // Exposes methods that are implemented by the WebBrowser control 
   // Searches for the specified field, using the specified binding constraints.
   FieldInfo fld = typeof(WebBrowser).GetField("_axIWebBrowser2", BindingFlags.Instance | BindingFlags.NonPublic);
   if (fld == null)
       return;
   object obj = fld.GetValue(wb);
   if (obj == null)
       return;
// Silent: Sets or gets a value that indicates whether the object can display dialog boxes.
// HRESULT IWebBrowser2::get_Silent(VARIANT_BOOL *pbSilent);HRESULT IWebBrowser2::put_Silent(VARIANT_BOOL bSilent);
     obj.GetType().InvokeMember("Silent", BindingFlags.SetProperty, null, obj, new object[] { true });
}

ObservableCollection Example WPF

WPF > Controls  > ObservableCollection

ObservableCollection is a dynamic data collection with automatic notifications when items are added, removed, or updated.


Example: Very simple ObservableCollection

In this example we will create a new class named Person and a list of persons using ObservableCollection. Using a DataGrid we will set only a property ItemsSource.  When press Add button the grid is automatically update. Please also see OnCollectionChanged event in which we can display some status of operations.

XAML:

    <Grid>
        <Label Content="First Name" HorizontalAlignment="Left" Margin="9,0,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtFname" HorizontalAlignment="Left" Height="23" Margin="10,26,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="216"/>
        <Label Content="Last Name" HorizontalAlignment="Left" Margin="10,59,0,0" VerticalAlignment="Top"/>
        <TextBox x:Name="txtLname" HorizontalAlignment="Left" Height="23" Margin="11,85,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="215"/>
        <Button x:Name="btnAdd" Content="Add" HorizontalAlignment="Left" Margin="151,127,0,0" VerticalAlignment="Top" Width="75" Click="btnAdd_Click"/>
        <DataGrid x:Name="dgPerson" HorizontalAlignment="Left" Margin="242,10,0,0" VerticalAlignment="Top" Height="300" Width="552"/>
        <Label x:Name="lblStatus" Content="" HorizontalAlignment="Left" Margin="0,284,0,0" VerticalAlignment="Top" Width="226"/>
    </Grid>
 
C# Code:


    public partial class MainWindow : Window
    {
        public class Person
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        private ObservableCollection<Person> persons = new ObservableCollection<Person>();

        public MainWindow()
        {

            InitializeComponent();
            dgPerson.ItemsSource = persons;
            persons.CollectionChanged += this.OnCollectionChanged;

        }
        void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            //Get the sender observable collection
            ObservableCollection<Person> obsSender = sender as ObservableCollection<Person>;
            NotifyCollectionChangedAction action = e.Action;
            if (action == NotifyCollectionChangedAction.Add)
                lblStatus.Content = "New person added";
            if (action == NotifyCollectionChangedAction.Remove)
                lblStatus.Content = "Person deleted";
        }
        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Person p = new Person();
            p.FirstName = txtFname.Text;
            p.LastName = txtLname.Text;
            persons.Add(p);

        }
    }

Thursday, October 31, 2013

WPF RepeatButton

WPF > Controls  > ContentControl > RepeatButton

WPF RepeatButton raises its Click event repeatedly from the time it is pressed until it is released.

Properties
  • Interval: gets or sets the amount of time, in milliseconds, between repeats once repeating starts
  • Delay: gets or sets the amount of time, in milliseconds, the RepeatButton waits while it is pressed before it starts repeating
WPF RepeatButton Example:

XAML:

<Grid>
        <RepeatButton Margin="10,10,0,0" VerticalAlignment="Top"
              Delay="500" Interval="500"
              HorizontalAlignment="Left"                      
              x:Name="btnIncrease"  Width="352" Height="30" Click="GrowButton_Click">
            RepeatButton: Click on this button and keep mouse pressed
        </RepeatButton>
        <TextBlock x:Name="txt" HorizontalAlignment="Left" Margin="10,55,0,0" TextWrapping="Wrap" Text="TextBlock"
                   VerticalAlignment="Top" Height="18" Width="352" RenderTransformOrigin="0.5,0.5">
        </TextBlock>
</Grid>

C# Code:

public partial class MainWindow : Window
    {
        int k = 0;
        public MainWindow()
        {
            InitializeComponent();
        }
        private void GrowButton_Click(object sender, RoutedEventArgs e)
        {
            k += 1;
            txt.Text = k.ToString() ;
        }
    }

Wednesday, October 30, 2013

WPF ScrollViewer

WPF > Controls  > ContentControl > ScrollViewer

WPF ScrollViewer control enables scrolling of content.
Sometimes the content is larger than a computer screen display area. This control encapsulates ScrollBar elements and a content container.

WPF ScrollViewer Example:

XAML:

<Window x:Class="ScrollViewer.MainWindow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="MainWindow" Height="406" Width="411">
    <ScrollViewer HorizontalScrollBarVisibility="Auto"   VerticalScrollBarVisibility="Auto">
       <StackPanel VerticalAlignment="Top" HorizontalAlignment="Left">
           <TextBlock TextWrapping="Wrap">ScrollViewer Example. Resize the window to see functionality</TextBlock>
           <Rectangle Fill="Blue" Width="400" Height="400"></Rectangle>
       </StackPanel>
   </ScrollViewer>
</Window>


WPF Window

WPF > Controls  > ContentControl > Window

A Windows Presentation Foundation (WPF) Window represents interaction between a user and a standalone application.
WPF window has two areas:
  • A non-client area (title, icon, buttons, border)
  • A client area (application content)

WPF Window Example:

In this example we will create a transparent window with opacity of 80%.

XAML:

<Window x:Class="ButtonExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" Opacity="0.8" AllowsTransparency="True" WindowStyle="None" Background="#FFEEE4E4"
        WindowStartupLocation="CenterScreen">
    <Grid>
        <Button Content="Close" HorizontalAlignment="Left" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
    </Grid>
</Window>

C# Code:

private void Button_Click(object sender, RoutedEventArgs e)
{  
  this.Close();
}