Featured Post

Organize and rename photos by EXIF data with PowerShell

This PowerShell script organizes and renames all photos in a selected folder using EXIF data. It will also create thumbnails of the images i...

Showing posts with label WPF. Show all posts
Showing posts with label WPF. Show all posts

Friday, December 27, 2013

Change TabControl SelectedTabItem in your ViewModel by TabItem Name or Header Value

Using these simple methods you can change your active tab in your ViewModel via commands or methods. If you want to change to a tab but don't want to have to track the tab index, you simply use the method that accepts the Tab Name or Header string name to change to that tab.

XAML:
<TabControl x:name="MyTabControl">...</TabControl>

Code Behind:
public MyUserControlorViewConstructor()
{
    InitializeComponent();
    
    MyViewModel mvm = new MyViewModel();
    DataContext = mvm;
    
    mvm.MyTabControl = MyTabControl;    
}

ViewModel:
public TabControl MyTabControl { get; set; }

public static void SetSelectedTab(string tabName)
{
    for (int i = 0; i < MyTabControl.Items.Count; i++)
    {
        TabItem item = MyTabControl.Items.GetItemAt(i) as TabItem;
        if (null == item || (item.Name != tabName && item.Header.ToString() != tabName)) continue;  
        MyTabControl.SelectedIndex = i;
        item.IsSelected = true;
        return;
    }
}

public static void SetSelectedTab(int tabIndex)
{
    TabItem item = MyTabControl.Items.GetItemAt(tabIndex) as TabItem;
    if (item == null) return;
    item.IsSelected = true;
    MyTabControl.SelectedIndex = tabIndex;
}

Tuesday, October 29, 2013

BackgroundWorker Example for C#/WPF

Here is a simple example of how to use a BackgroundWorker to execute long running tasks without freezing the UI. This allows you to use ProgressChanged event handler to change your UI with status messages making for a much friendlier user experience.

In this example I am creating and populating a database which takes a minute or so to complete. With my Simple Elegant Busy Indicator for WPF bound to the BusyIndicator property, it lets the user know the application is busy and not frozen.


private void Execute()
{
    // Set status
    BusyIndicator = true;
    Status = "Creating database, please wait. This may take several minutes...";

    // Create Database background worker
    CreateDatabaseWorker = new BackgroundWorker();
    CreateDatabaseWorker.WorkerReportsProgress = true;
    CreateDatabaseWorker.DoWork += new DoWorkEventHandler(CreateDatabase_DoWork);
    CreateDatabaseWorker.ProgressChanged += new ProgressChangedEventHandler(CreateDatabase_WorkerProgressChanged);
    CreateDatabaseWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(CreateDatabase_WorkCompleted);
    CreateDatabaseWorker.RunWorkerAsync();
}

// Note: You cannot modify any UI bound property in the _DoWork method
private void CreateDatabase_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        // Long running methods go here
        CreateDatabaseWorker.ReportProgress(25, "Creating employees...");
        Utilities.PopulateDBModel.CreateInitialEmployees();

        CreateDatabaseWorker.ReportProgress(50, "Creating countries and regions...");
        Utilities.PopulateDBModel.CreateCountries();
    }
    catch (Exception ex)
    {
        // If anything fails we set our result to false
        CreateDatabaseWorker.ReportProgress(100, "Error...");
        e.Result = false;
        return;
    }
    e.Result = true;
}

// This will update our UI while our background worker is... working
private void CreateDatabase_WorkerProgressChanged(object sender, ProgressChangedEventArgs e)
{
    if (e.UserState != null)
    {
        ProgressBarValue = e.ProgressPercentage;
        Status = e.UserState.ToString();
    }
}

// Now we can evaluate our results
private void CreateDatabase_WorkCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    BusyIndicator = false;

    if ((bool)e.Result != true)
    {
        ShowFailure = true;
        return;
    }

    ShowSuccess = true;
    Status = "Database created successfully!";
}

Friday, October 18, 2013

Simple Elegant Busy Indicator for WPF

<Control Grid.Column="0" Grid.Row="3"
            Grid.ColumnSpan="1" Grid.RowSpan="1"
            Width="100" Height="100" VerticalAlignment="Top"  HorizontalAlignment="Left">
    <Control.Style>
        <Style TargetType="Control">
            <Setter Property="Foreground" Value="White" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Control">
                        <Viewbox>
                            <Canvas RenderTransformOrigin="0.5,0.5" Width="100" Height="100">
                                <Canvas.Resources>
                                    <Style TargetType="{x:Type Ellipse}">
                                        <Setter Property="Stretch" Value="Fill"/>
                                        <Setter Property="Fill" Value="Black"/>
                                    </Style>
                                </Canvas.Resources>
                                <Ellipse Width="21.835" Height="21.862" Canvas.Left="20.1696" Canvas.Top="9.76358" Opacity="1.0"/>
                                <Ellipse Width="20.835" Height="20.862" Canvas.Left="2.86816" Canvas.Top="29.9581" Opacity="0.9"/>
                                <Ellipse Width="19.835" Height="19.862" Canvas.Left="0.00001" Canvas.Top="57.9341" Opacity="0.8"/>
                                <Ellipse Width="17.835" Height="17.862" Canvas.Left="12.1203" Canvas.Top="83.3163" Opacity="0.7"/>
                                <Ellipse Width="16.835" Height="16.862" Canvas.Left="36.5459" Canvas.Top="98.1380" Opacity="0.6"/>
                                <Ellipse Width="14.835" Height="14.862" Canvas.Left="64.6723" Canvas.Top="96.8411" Opacity="0.5"/>
                                <Ellipse Width="13.835" Height="13.862" Canvas.Left="87.6176" Canvas.Top="81.2783" Opacity="0.4"/>
                                <Ellipse Width="12.835" Height="12.862" Canvas.Left="98.165"  Canvas.Top="54.4140" Opacity="0.3"/>
                                <Ellipse Width="11.835" Height="11.862" Canvas.Left="92.9838" Canvas.Top="26.9938" Opacity="0.2"/>
                                <Canvas.RenderTransform>
                                    <RotateTransform x:Name="SpinnerRotate" Angle="0"/>
                                </Canvas.RenderTransform>
                                <Canvas.Triggers>
                                    <EventTrigger RoutedEvent="ContentControl.Loaded">
                                        <BeginStoryboard>
                                            <Storyboard>
                                                <DoubleAnimation Storyboard.TargetName="SpinnerRotate" Storyboard.TargetProperty="Angle" From="0" To="360" Duration="0:0:01.3" RepeatBehavior="Forever"/>
                                            </Storyboard>
                                        </BeginStoryboard>
                                    </EventTrigger>
                                </Canvas.Triggers>
                            </Canvas>
                        </Viewbox>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Control.Style>
</Control>

You can easily bind the Visibility to a property to control when it is shown/hidden:
Visibility="{Binding ShowThinking, Converter={StaticResource BooleanToVisibilityConverter}}"
Derived from: http://stackoverflow.com/a/8668682/1992193

Tuesday, October 8, 2013

C# WPF/Silverlight MVVM Beginners Tutorial 101 Part I

Welcome to a multi-part tutorial to help walk you through how to get started developing a WPF or Silverlight application utilizing the MVVM design pattern.

MVVM = Model, View, ViewModel

Our ViewModels primary role is to control the data displayed on our View, data pulled from our Model. The Microsoft Prism library supplies (among other things we can use later) the NotificationObject class which we will use to Notify our View when Properties Change.

Each of our ViewModels will inherit from our BaseViewModel class that we will create first.

Prerequisites

Using VisualStudio, start a New Project > Visual C# > Silverlight > Silverlight Application

Note: We use Silverlight for Web applications and WPF for Desktop applications. Most Silverlight controls are supported in WPF while there are some WPF controls that are not available in Silverlight, so it would be recommended to design your application using Silverlight to be compatible on both platforms. See Contrasting Silverlight and WPF for more information.

Using NuGet, install Prism to supply our NotifyPropertyChanged utilities:

Visual Studio > Tools > Library Package Manager > Package Manager Console

PM> Install-Package Prism

Now the Prism dll files have been added to your Project References folder and we can refer to the Prism Namespace in our code.

On to the code

Create a new Class: BaseViewModel.cs

At the top, include the Prism references, and the class inherits from Prism's NotificationObject:

BaseViewModel.cs:

using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.ViewModel;

namespace MyApp
{
    public class BaseViewModel : NotificationObject
    {
    }
}

Lets create a new Class: CarrotViewModel.cs

namespace MyApp
{
    public class CarrotViewModel : BaseViewModel
    {
    }
}

Because our CarrotViewModel inherits from our BaseViewModel, which inherits from Prism NotificationObject, any Property in our CarrotViewModel can now support RaisePropertyChanged method.

In Part II we will add some Properties and have them update our UI, after all that is the whole point of an application usually!

to be continued in Part II...