Wednesday, August 6, 2008

Change Title bar of a window from another thread

If you have to change the title bar of a Windows in WPF application from another thread, the following code snippet helps you.

Note:- In the given code snippet the title bar of a windows is changed when the user click on the Change Title button.

Create a user interface using the following code:-


<Window x:Class="WpfApplication1.Window1"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="Window1" Height="300" Width="300">

<Grid>

<Button Name="btnTitleChange" Content="Change Title" Width="100" Height="50" Click="btnTitleChange_Click">Button>

<Grid>

<Window>

Note:-

Now your user interface look like this:-


Now write the following code in the code file ie window1.xmal.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.Threading;

using System.Windows.Threading;


namespace WpfApplication1

{

///

/// Interaction logic for Window1.xaml

///

public partial class Window1 : Window

{

//

Window1 win;

public Window1()

{

InitializeComponent();

}


private void btnTitleChange_Click(object sender, RoutedEventArgs e)

{

Thread winTitle = new Thread(new ParameterizedThreadStart(DoWork));

winTitle.Start(this);

}

public void DoWork(object obj)

{

win = (Window1)obj;

win.Dispatcher.Invoke(DispatcherPriority.Normal, new Action(setTitle));

}

public void setTitle()

{

win.Title = "Windows Title Changed From Other Thread:-Amit Kumar";

}


}

}


Note:- Run the Application by pressing F5 functional key, and click on the Change Title button, the windows looks like this:-





No comments:

Is this blog solve your Problem?