I have a WPF application with several windows. I would like to define GLOBAL inputBindings.
To define LOCAL inputbindings, i just declare the input in Window.InputBindings or UserControl.InputBindings.
To define GLOBALs, I wish i could do the same with the Application class...
<Application
....>
<Application.InputBindings>
...
</Application.InputBindings>
If i have the same binding in 2 different windows, i have to code it twice. This doesn't meet D.R.Y.'s philosophy and i guess there is a better way...
EDIT : in his answer Kent Boogaart advices me to use Style. Unfortunately, i can't figure out how to define it. This is the code :
<Application.Resources>
<Style TargetType="Window">
<Setter Property="InputBindings">
<Setter.Value>
<Window.InputBindings>
<KeyBinding KeyGesture="Ctrl+M" Command="local:App.MsgCommand />
</Window.InputBindings>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
It raises an error : error MC3080: The Property Setter 'InputBindings' cannot be set because it does not have an accessible set accessor.
Is my style wrong?
Is there another solution?
Any ideas? thanks!
One solution is to use an Attached Property with a Style to set the InputBindings on all the controls of a given type in your application. Unfortunately, since you can't make a "catch-all" Style (that I know of, anyway), you'll have to create a Style for each control type on which you want to set the InputBindings (this shouldn't, however, be too many controls). Below is some sample code that shows how to do this:
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
public class MyAttached
{
public static readonly DependencyProperty InputBindingsProperty =
DependencyProperty.RegisterAttached("InputBindings", typeof(InputBindingCollection), typeof(MyAttached),
new FrameworkPropertyMetadata(new InputBindingCollection(),
(sender, e) =>
{
var element = sender as UIElement;
if (element == null) return;
element.InputBindings.Clear();
element.InputBindings.AddRange((InputBindingCollection)e.NewValue);
}));
public static InputBindingCollection GetInputBindings(UIElement element)
{
return (InputBindingCollection)element.GetValue(InputBindingsProperty);
}
public static void SetInputBindings(UIElement element, InputBindingCollection inputBindings)
{
element.SetValue(InputBindingsProperty, inputBindings);
}
}
}
<Application x:Class="WpfApplication1.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
StartupUri="Window1.xaml">
<Application.Resources>
<Style TargetType="TextBox">
<Setter Property="loc:MyAttached.InputBindings">
<Setter.Value>
<InputBindingCollection>
<KeyBinding Key="A" Modifiers="Ctrl" Command="loc:Window1.MyAction" />
</InputBindingCollection>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="Button">
<Setter Property="loc:MyAttached.InputBindings">
<Setter.Value>
<InputBindingCollection>
<KeyBinding Key="A" Modifiers="Ctrl" Command="loc:Window1.MyAction" />
</InputBindingCollection>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300">
<Window.CommandBindings>
<CommandBinding Command="loc:Window1.MyAction" Executed="MyAction_Executed" />
</Window.CommandBindings>
<StackPanel>
<Button Content="Try Ctrl+A Here!" />
<TextBox Text="Try Ctrl+A Here!" />
</StackPanel>
</Window>
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
public partial class Window1
{
public static readonly RoutedUICommand MyAction = new RoutedUICommand("MyAction", "MyAction", typeof(Window1));
public Window1() { InitializeComponent(); }
private void MyAction_Executed(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("MyAction!"); }
}
}
You could create a Style that is applied to all your Windows. That Style could set the InputBindings.
Related
I have a textbox with a default text. When I focus the textbox it is cleared so I can write, and if I unfocus without writing anything the default text reappears.
I also have two radiobuttons for selecting the language. The languages are provided as xaml resourcefiles and the default text in the textbox is connected to that using DynamicResource.
My problem is that the language change only work as long as I haven't focused the textbox. If I focus the textbox and then unfocus it without changing anything, the textbox no longer changes language.
I'm guessing that is because once it's changed (cleared) it's no longer linked to the dynamic resource, because WPF considers my onfocus changes as user input, but I can't figure out how to get around that and make it change language even if I've clicked the textbox.
The second textbox don't have any focus behaviour and in that one the language change works as it should, i.e. it changes the language as long as I haven't actually written something.
MainWindow xaml:
<Window x:Class="Textbox_langauge_buggseek.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Textbox_langauge_buggseek"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBox x:Name="TextBox" HorizontalAlignment="Left" Height="46" Margin="84,55,0,0" TextWrapping="Wrap" Text="{DynamicResource ResourceKey=TB}" VerticalAlignment="Top" Width="334" GotFocus="TextBox_GotFocus" LostFocus="TextBox_LostFocus"/>
<TextBox x:Name="TextBox_Copy" HorizontalAlignment="Left" Height="46" Margin="84,123,0,0" TextWrapping="Wrap" Text="{DynamicResource ResourceKey=TB}" VerticalAlignment="Top" Width="334"/>
<RadioButton x:Name="En" Content="En" GroupName="Lang" HorizontalAlignment="Left" Margin="391,216,0,0" VerticalAlignment="Top" Checked="En_Checked" IsChecked="True"/>
<RadioButton x:Name="Se" Content="Se" GroupName="Lang" HorizontalAlignment="Left" Margin="391,234,0,0" VerticalAlignment="Top" Checked="Se_Checked"/>
</Grid>
</Window>
MainWindows cs:
using System;
using System.Windows;
using System.Windows.Controls;
namespace Textbox_langauge_buggseek
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetLanguageDictionary();
}
//*****************************************************************************************
private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox box = sender as TextBox;
box.Text = box.Text == (string)this.Resources["TB"] ? string.Empty : box.Text;
}
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
TextBox box = sender as TextBox;
box.Text = box.Text == string.Empty ? (string)this.Resources["TB"] : box.Text;
}
//*****************************************************************************************
private void En_Checked(object sender, RoutedEventArgs e)
{
SetLanguageDictionary("En");
}
private void Se_Checked(object sender, RoutedEventArgs e)
{
SetLanguageDictionary("Se");
}
//*****************************************************************************************
private void SetLanguageDictionary(string language = "En")
{
ResourceDictionary dict = new ResourceDictionary();
switch (language)
{
case "Se":
dict.Source = new Uri("..\\Resources\\Se.xaml", UriKind.Relative);
break;
default:
dict.Source = new Uri("..\\Resources\\En.xaml", UriKind.Relative);
break;
}
this.Resources.MergedDictionaries.Add(dict);
}
}
}
En language xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String x:Key="TB">Text in the TextBox!</system:String>
</ResourceDictionary>
Se language xaml:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:system="clr-namespace:System;assembly=mscorlib">
<system:String x:Key="TB">Text i textrutan!</system:String>
</ResourceDictionary>
Yes, when you set TextBox.Text in codebehind, the text does not know anymore that it has to take a value from the Rersource. To avoid it you can change the text using pure XAML, with Triggers.
Remove TextBox's event handlers and add a style like this:
<TextBox x:Name="TextBox" HorizontalAlignment="Left" Height="46" Margin="84,55,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="334">
<TextBox.Style>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="true">
<Setter Property="Text" Value="" />
</Trigger>
<Trigger Property="IsFocused" Value="false">
<Setter Property="Text" Value="{DynamicResource ResourceKey=TB}" />
</Trigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
Hope someone can enlighten me on the best mvvm practice using service locator.
Base principles are clear. I have my views with corresponding view model, everything works at it should.
Lets make a simple example. I have one main window and 2 user controls UCA and UCB. Each of them have view model registered in the locator class.
Using this IoC pattern how can you display UCA and UCB in the main window using one content control and binding through main window view model? To be precise I want to show only one control at the same time. I can't bind the UCA or UCB view model because this is view first approach, the view is not automatically resolved.
What is the correct approach for this?
Thanks
You can create a separate service for launching views as dialog, so that it can be used in a generic way across the application. And will inject this service to the ViewModel via Constructor which wants to launch any dialog.
public interface IDialogService<T>
{
void Show();
void ShowDialog();
}
public class DialogService<T> : IDialogService<T> where T : Window
{
public void Show()
{
container.Resolve<T>().Show();
}
public void ShowDialog()
{
container.Resolve<T>().ShowDialog();
}
}
Now just inject this service to the respective viewmodel.
public class YourViewModel
{
//commands
public ICommand someCommand { get; set; }
private IDialogService<BookingView> _dialogService;
public YourViewModel(IDialogService<YourView > dialogService)
{
_dialogService = dialogService
someCommand = new RelayCommand(someCommandDoJob, () => true);
}
public void someCommandDoJob(object obj)
{
//Since you want to launch this view as dialog you can set its datacontext in its own constructor.
_dialogService.ShowDialog();
}
}
One solution could be using ContentTemplate property together with DataTrigger to selectively show UCA or UCB (see example below). UCA could also be set as default view in a style setter. In this case only one DataTriggers is needed.
Another solution could be using ContentTemplateSelector property and implement a DataTemplateSelector.
See: ContentControl.ContentTemplateSelector (MSDN)
<!--content control in main window-->
<ContentControl>
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<!--suppose main window view model has a bool property UseUCA-->
<!--if UseUCA is true render UCA view-->
<DataTrigger Binding="{Binding UseUCA}" Value="True">
<DataTrigger.Setters>
<!--by setting ContentTemplate property you control what is rendered inside of the content control-->
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<!--render UCA view-->
<local:UCA />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger.Setters>
</DataTrigger>
<!--if UseUCA is false render UCB view-->
<DataTrigger Binding="{Binding UseUCA}" Value="False">
<DataTrigger.Setters>
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<!--render UCB view-->
<local:UCB />
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
OK... here is a thought... you can keep track of the "currentview" in your MainViewModel and let the UI show the correct control based on type. Here is a quick example. I am using a Button to switch views... this could ideally be done via any logic that fits your requirements.
MainWindow:
<Window x:Class="WpfApplication4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication4"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Switch Views" Command="{Binding SwitchViewsCommand}" />
<ContentControl Grid.Row="1" Content="{Binding CurrentControl}">
</ContentControl>
</Grid>
</Window>
UCA and UCB are simply user controls with different text in them:
<UserControl x:Class="WpfApplication4.UserControls.UCA"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:WpfApplication4.UserControls"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<TextBlock Text="This is user control A" />
</Grid>
</UserControl>
UCAViewModel and UCBViewModel are empty viewmodels in my example that inherit from ViewModelBase
namespace WpfApplication4.ViewModel
{
public class UCAViewModel : ViewModelBase
{
}
}
The MainViewModel handles the currently shown view based on its viewmodel
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Microsoft.Practices.ServiceLocation;
namespace WpfApplication4.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
RegisterCommands();
SwitchView();
}
private void SwitchView()
{
if(CurrentControl == null)
{
CurrentControl = ServiceLocator.Current.GetInstance<UCAViewModel>();
}
else
{
if(CurrentControl is UCAViewModel)
CurrentControl = ServiceLocator.Current.GetInstance<UCBViewModel>();
else
CurrentControl = ServiceLocator.Current.GetInstance<UCAViewModel>();
}
}
private ViewModelBase _currentControl;
public ViewModelBase CurrentControl
{
get { return _currentControl; }
set
{
if (_currentControl != value)
{
_currentControl = value;
RaisePropertyChanged("CurrentControl");
}
}
}
private void RegisterCommands()
{
SwitchViewsCommand = new RelayCommand(SwitchView);
}
public RelayCommand SwitchViewsCommand { get; private set; }
}
}
the ViewModelLocator stores the instances
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
namespace WpfApplication4.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<UCAViewModel>();
SimpleIoc.Default.Register<UCBViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
And finally, the glue that makes the correct view show is done in the app.xaml file:
<Application x:Class="WpfApplication4.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication4" StartupUri="MainWindow.xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:localUC="clr-namespace:WpfApplication4.UserControls"
xmlns:vm="clr-namespace:WpfApplication4.ViewModel">
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />
<DataTemplate DataType="{x:Type vm:UCAViewModel}">
<localUC:UCA />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:UCBViewModel}">
<localUC:UCB />
</DataTemplate>
</Application.Resources>
</Application>
I have a MainWindow in my application. The MainWindow hosts a UserControl in its ContentControl(I call this MainPage). MainPage goes onto hosts another UserControl which contains all sorts of controls on it (KiviPage).
I am trying to connect to a database in MainPage and load a file in the KiviPage. If any of the two operations fail (connection to database or file loading) I have to quit the application. Which means I have to quit the application from the user controls.
Whats the best way to do this?
Simply call "Shutdown" from code behind of the user control:
Application.Current.Shutdown();
I think, you may implement this action through a attached DependencyProperty. Something like that (it's a simple work example):
XAML
<Window x:Class="ShutdownAppHelp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ShutdownAppHelp"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style TargetType="{x:Type CheckBox}">
<Style.Triggers>
<Trigger Property="IsChecked" Value="True">
<Setter Property="local:ProgramBehaviours.Shutdown" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Grid>
<CheckBox Content=" Shutdown" IsChecked="False" />
</Grid>
</Window>
Code behind
namespace ShutdownAppHelp
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
public static class ProgramBehaviours
{
// Shutdown program
public static void SetShutdown(DependencyObject target, bool value)
{
target.SetValue(ShutdownProperty, value);
}
public static readonly DependencyProperty ShutdownProperty =
DependencyProperty.RegisterAttached("Shutdown",
typeof(bool),
typeof(ProgramBehaviours),
new UIPropertyMetadata(false, OnShutdown));
// Here call function in UIPropertyMetadata()
private static void OnShutdown(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
if (e.NewValue is bool && ((bool)e.NewValue))
{
Application.Current.Shutdown();
}
}
}
}
You can put any kind of behavior in DependencyProperty, which is available only through the code and call it a XAML:
<DataTrigger Binding="{Binding ElementName=SomeControl, Path=Tag}" Value="Shutdown">
<Setter Property="local:ProgramBehaviours.Shutdown" Value="True" />
</DataTrigger>
Also, you can access it directly through the code of behavior:
ProgramBehaviours.SetShutdown(SomeControl, Value);
Or from XAML without condition:
<SomeControl local:ProgramBehaviours.SetShutdown="True" ... />
How do I bind something like <Color x:Key="SomeColor" /> to a dependency property with Caliburn Micro?
I need to be able to change Color at run-time and have it immediately updated in all things that use it.
Solution:
XAML in SomeClassView.xaml
<SomeControl.Resources>
<SolidColorBrush x:Key="ControlBrush" />
</SomeControl.Resources>
C# in SomeClassViewModel.cs
[Export(typeof(MainWindowViewModel))]
public class MainWindowViewModel : PropertyChangedBase
{
private SolidColorBrush _controlBrush;
public SolidColorBrush ControlBrush
{
get { return _controlBrush; }
set
{
_controlBrush = value;
NotifyOfPropertyChange(() => ControlBrush);
}
}
}
The problem was exactly what Charleh said, I just totally forgot that not everything in WPF can be a DependencyProperty.
You can't usually directly bind a Color object, you need to use a SolidColorBrush (for solid colour), as that's what most UI objects expect.
e.g.
TextBox.Background expects Brush, of which SolidColorBrush is a subclass of. There are other types of brushes that produce different fills such as LinearGradientBrush
Have a look here:
How can I bind a background color in WPF/XAML?
Can you provide some screenshots of what you expect and the XAML?
Edit:
Ok well what you want is pretty simple to achieve, not really related to Caliburn.Micro at all :)
Create your styles as usual, but bind the brushes Color property dynamically using DynamicResource. When you update the colour itself, the resource binding will be evaluated again and the colours will change.
Example XAML:
<Window x:Class="WpfApplication1.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">
<Window.Resources>
<Color x:Key="TestColor" A="255" R="255" G="0" B="0"></Color>
<Style x:Key="ButtonStyle" TargetType="Button">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="{DynamicResource TestColor}"></SolidColorBrush>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<StackPanel>
<Button Click="Button_Click" Style="{StaticResource ButtonStyle}">Red</Button>
<Button Click="Button_Click_1" Style="{StaticResource ButtonStyle}">Blue</Button>
</StackPanel>
</Grid>
</Window>
Code-behind:
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Resources["TestColor"] = Color.FromArgb(255, 255, 0, 0);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
Resources["TestColor"] = Color.FromArgb(255, 0, 0, 255);
}
}
}
I am trying to rename a column in WPF data grid. I am providing context-menu to user for column rename. Once user clicks on the rename from a column-header of particular column, I am applying a style to the column-header using following code and style.
private void RenameColumn_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (e != null)
{
if (e.Parameter != null)
{
if ((e.Parameter as DataGridColumnHeader) != null)
{
this.DefaultColHeaderStyle = (e.Parameter as DataGridColumnHeader).Style;
this.RenamedColIndex = (e.Parameter as DataGridColumnHeader).DisplayIndex;
(this.grTestData.ColumnFromDisplayIndex(this.RenamedColIndex)).HeaderStyle = this.grTestData.Resources["RenameColumnHeader"] as Style;
}
}
}
}
I am binding this text-box to a properpty:
<Style x:Key="RenameColumnHeader" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid FocusManager.FocusedElement="{Binding ElementName=txtBxRename}">
<TextBox x:Name="txtBxRename" GotFocus="txtBxRename_GotFocus" LostFocus="txtBxRename_LostFocus" KeyDown="txtBxRename_KeyDown" TextChanged="txtBxRename_TextChanged" Text="{Binding Path=NewColName,Mode=TwoWay}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I have implemented INotifyPropertyChanged interface for property NewColName:
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public string NewColName
{
get
{
return this.newColName;
}
set
{
this.newColName = value;
this.OnPropertyChanged("NewColName");
}
}
but it is not triggering the property-changed when i start typing in the text-box. I am trying to implement IDataErrorInfo for the text-box validation. Please guide me. Do let me know if you need any other information about my code.
You probably will need to set the Binding.UpdateSourceTrigger to PropertyChanged, as for TextBox.Text it is LostFocus by default.
It has been solved.
Whenever we are binding a control declared within a style, we need to give a name to the window.
<Window x:Class="DataGridColumnRename.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cmd="clr-namespace:DataGridColumnRename"
Title="MainWindow" Height="350" Width="525" Name="Me">
And in the control within the style we need to specify the ElementName Property and assign windown name (in this case it is 'Me') to it.
<Style x:Key="RenameColumnHeader" TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid FocusManager.FocusedElement="{Binding ElementName=txtBxRename}">
<TextBox x:Name="txtBxRename" GotFocus="txtBxRename_GotFocus" LostFocus="txtBxRename_LostFocus" KeyDown="txtBxRename_KeyDown" Text="{Binding ElementName=Me, Path=NewColName,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
Then only it triggers INotifyPropertyChanged. :) :) Thanks for the help guys.