Unable to fire InvokeCommandAction - wpf

On click of a textblock, I want to lift its contents in my view model and if accurate, navigate to another page. Unfortunately for me, the click event never triggers its bound command. Below is my code
In the xaml, I have this markup
<UserControl x:Class="SchoolPrism.Login.Views.Login"
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:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:SchoolPrism.Login.Views"
xmlns:prism="http://prismlibrary.com/"
xmlns:constants="clr-namespace:Infrastructure.Constants;assembly=SchoolPrismInfrastructure"
xmlns:login="clr-namespace:SchoolPrism.Login.ViewModel"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<!-- when we have a view model, bind to that instead-->
<Grid DataContext="{Binding login:LoginViewModel}">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="5*"/>
</Grid.RowDefinitions>
<TextBlock DataContext="{Binding}" Text="{Binding FormResults}"></TextBlock>
<TextBlock Text="hi, can you see me?" x:Name="SchoolCode" Grid.RowSpan="2" Margin="0,50,0,0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewMouseDown">
<!--tried replacing interactivity with prism here but it had no effect -->
<i:InvokeCommandAction Command="{Binding submitForm}" CommandParameter="{Binding Text, ElementName=SchoolCode}" ></i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</Grid>
</UserControl>
Then, in the view model, I have this
using Prism.Commands;
using Prism.Modularity;
using SchoolPrism.Modules.Login;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace SchoolPrism.Login.ViewModel
{
class LoginViewModel
{
ICommand submitForm
{
get { return new DelegateCommand<string>(SubmitForm); }
}
public void SubmitForm(string code)
{
// interact with model over given code
// if auth, get module instance and invoke the following
new LoginModule().proceedToNext("AllTopics");
}
}
}
Finally, in the module proper, I have
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using Prism.Commands;
using Prism.Modularity;
using Prism.Mvvm;
using Prism.Regions;
using SchoolPrism.Login.Views;
using System;
using System.Windows;
using System.Windows.Input;
namespace SchoolPrism.Modules.Login
{
[Module(ModuleName = "LoginModule")]
class LoginModule : BindableBase, IModule
{
IRegionManager _regionMan;
// this method is called on our behalf by prism
public void Initialize ()
{
_regionMan = ServiceLocator.Current.GetInstance<iregionmanager>();
}
public void proceedToNext (string target)
{
_regionMan.RequestNavigate("LoginForm", new Uri(target, UriKind.Relative)/*, (NavigationResult result) => { return code.Length > 0; }*/);
}
}
}

The fault is from this line
<Grid DataContext="{Binding login:LoginViewModel}">
This is acceptable for binding to properties and not to the contexts themselves. Unfortunately, the compiler doesn't complain. The appropriate syntax for binding to a context is
<Control.DataContext>
<namespace:ContextObj>
</Control.DataContext>
which in this case would be:
<Grid.DataContext>
<login:LoginViewModel></login:LoginViewModel>
</Grid.DataContext>

Related

Remove an attribute from xaml using c# - WPF

This question is related to removing an attribute in xaml.
In the below code, I have a Span. During an event, I add a back ground to this Span. During another event, I need to remove it. Please let me know, if there is a way to remove the background attribute I set to Span.
My Xaml looks like this.
<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">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<RichTextBox x:Name="rtb">
<FlowDocument>
<Paragraph>
<Span x:Name="def" Tag="default">
<Run x:Name="deg">Some Text</Run>
</Span>
</Paragraph>
</FlowDocument>
</RichTextBox>
<TextBox x:Name="tx" Grid.Row="1" TextWrapping="Wrap"/>
<Grid Grid.Row="2">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Content="s" Click="Button_Click"/>
<Button Content="bg-Add" Grid.Column="1" Click="Button_Click"/>
<Button Content="bg-Remove" Grid.Column="2" Click="Button_Click"/>
</Grid>
</Grid>
</Window>
My code looks like this.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows. Shapes;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if ((sender as Button).Content.ToString() == "s")
{
tx.Text = XamlWriter.Save(def);
}
else if ((sender as Button).Content.ToString() == "bg-Add")
{
def.Background = new SolidColorBrush(Colors.Blue);
}
else if ((sender as Button).Content.ToString() == "bg-Remove")
{
//Need to remove the set back color so that I get the default back
}
}
}
}
I am able to find an answer myself.
def.ClearValue(Span.BackgroundProperty);
is going to remove that attribute for me.
You can override ShouldSerializeProperty
public class CustomizedSpan : Span
{
public bool IsRemoveBackGround;
protected override bool ShouldSerializeProperty(DependencyProperty dp)
{
if (dp == Span.BackgroundProperty && IsRemoveBackGround)
{
return false;
}
else
{
return base.ShouldSerializeProperty(dp);
}
}
}

Contents of Content Control gone on tab switch

I am using mvvm. I am loading a usercontrol that contains a content control on two different tabs like so:
<TabControl>
<TabItem Header="View">
<StackPanel>
<Info:UserData/><!--UserData Control-->
<Button Content="View Entries" Command="{Binding BeginView}"/>
</StackPanel>
</TabItem >
<TabItem Header="Edit">
<StackPanel>
<Info:UserData/><!--UserData Control-->
<Button Content="Edit Entries" Command="{Binding BeginEdit}"/>
</StackPanel>
</TabItem >
</TabControl>
The User Control looks like:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ContentControl Grid.Row="0" Content="{Binding UserTypeInfo}"/>
<Info:UserDetailsArea Grid.Row="1"/>
</Grid>
When the tab first loads the content of the ContentControl is set to an image. Depending on some actions the content may change to a datatable, video, etc. This part works fine.
When it loads the default tab is the first one. If I click on the second tab, you should see the same thing - with a different button, this works. But if I go back to the first tab the Content control is empty.
What do I need to do so that both tabs display the image?
The value bound to from the viewmodel as requested:
private object userTypeInfo
/// <summary>
/// User Specific data
/// </summary>
public object UserTypeInfo
{
get
{
return userTypeInfo;
}
private set
{
UuserTypeInfo= value;
OnPropertyChanged("UserTypeInfo");
}
}
Edit:
The following is a simplified example that I believe shows the same problem:
XAML code for window:
<Window x:Class="dualCC.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"
Loaded="Window_Loaded">
<Grid>
<TabControl>
<TabItem Header="One">
<StackPanel>
<Button Content="One" />
<ContentControl Name="CCone"/>
</StackPanel>
</TabItem>
<TabItem Header="Two">
<StackPanel>
<Button Content="Two" />
<ContentControl Name="CCtwo"/>
</StackPanel>
</TabItem>
</TabControl>
</Grid>
</Window>
Code behind (you'll need to fix the path to an image):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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;
namespace dualCC
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(#"C:\Image.jpg");
BitmapImage temp = new BitmapImage(uri);
Image CurrentImage = new Image();
CurrentImage.Source = temp;
CCone.Content = CurrentImage;
CCtwo.Content = CurrentImage;
}
}
}
This isn't MVVM. In MVVM you never manipulate GUI elements directly in code-behind like this.
To answer your question, the problem is that you're creating an Image, which is actually a child control, and setting it as the content of two separate controls. Controls can only have one parent. Create separate Images instead and set the BitmapImage as the source for each:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Uri uri = new Uri(#"C:\Image.jpg");
BitmapImage temp = new BitmapImage(uri);
CCone.Content = new Image { Source = temp };
CCtwo.Content = new Image { Source = temp };
}
Or better yet use proper MVVM and do it with data binding.

WPF: Dynamic views based on button clicks

I am a newbie to WPF and while I have read lots of theory and articles, I am unable to put it all together in a working solution.
Presently, I wish to implement dynamic multiple views in a window which could be selected by the user using buttons. The target is very much like one given in the question,
WPF : dynamic view/content
Can somebody please share with me a working code, of simplest implementation of the above. Just a window which contains two grids - one grid has two buttons - second grid changes background color depending on which button is clicked. From there on , I can take things further.
Thank you very much.
Use MVVM
It's a design approach. Basically you treat your Window as shell, and it's responsible for swapping views.
To simplify this snippet, I've referenced MvvmLight .
The Window contains ContentControl which dynamically displays the relevant view
Each dynamic view can communicate with the shell Window (using MvvmLight's Messenger) and tell it to change the view to something else.
MainWindow.xaml
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:MainWindowViewModel></local:MainWindowViewModel>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Button Grid.Row="0" Grid.Column="0" Command="{Binding ChangeFirstViewCommand}">Change View #1</Button>
<Button Grid.Row="0" Grid.Column="1" Command="{Binding ChangeSecondViewCommand}">Change View #2</Button>
<ContentControl Grid.Row="1" Grid.ColumnSpan="2" Content="{Binding ContentControlView}"></ContentControl>
</Grid>
</Window>
MainWindowViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
public class MainWindowViewModel : ViewModelBase
{
private FrameworkElement _contentControlView;
public FrameworkElement ContentControlView
{
get { return _contentControlView; }
set
{
_contentControlView = value;
RaisePropertyChanged("ContentControlView");
}
}
public MainWindowViewModel()
{
Messenger.Default.Register<SwitchViewMessage>(this, (switchViewMessage) =>
{
SwitchView(switchViewMessage.ViewName);
});
}
public ICommand ChangeFirstViewCommand
{
get
{
return new RelayCommand(() =>
{
SwitchView("FirstView");
});
}
}
public ICommand ChangeSecondViewCommand
{
get
{
return new RelayCommand(() =>
{
SwitchView("SecondView");
});
}
}
public void SwitchView(string viewName)
{
switch (viewName)
{
case "FirstView":
ContentControlView = new FirstView();
ContentControlView.DataContext = new FirstViewModel() { Text = "This is the first View" };
break;
default:
ContentControlView = new SecondView();
ContentControlView.DataContext = new SecondViewModel() { Text = "This is the second View" };
break;
}
}
}
}
FirstView.xaml
<UserControl x:Class="WpfApplication1.FirstView"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<Label>This is the second view</Label>
<Label Content="{Binding Text}" />
<Button Command="{Binding ChangeToSecondViewCommand}">Change to Second View</Button>
</StackPanel>
</UserControl>
FirstViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfApplication1
{
public class FirstViewModel : ViewModelBase
{
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
RaisePropertyChanged("Text");
}
}
public ICommand ChangeToSecondViewCommand
{
get
{
return new RelayCommand(() =>
{
Messenger.Default.Send<SwitchViewMessage>(new SwitchViewMessage { ViewName = "SecondView" });
});
}
}
}
}
SecondView.xaml
<UserControl x:Class="WpfApplication1.SecondView"
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"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel>
<Label>This is the second view</Label>
<Label Content="{Binding Text}" />
<Button Command="{Binding ChangeToFirstViewCommand}">Change to First View</Button>
</StackPanel>
</UserControl>
SecondViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace WpfApplication1
{
public class SecondViewModel : ViewModelBase
{
private string _text;
public string Text
{
get { return _text; }
set
{
_text = value;
RaisePropertyChanged("Text");
}
}
public ICommand ChangeToFirstViewCommand
{
get
{
return new RelayCommand(() =>
{
Messenger.Default.Send<SwitchViewMessage>(new SwitchViewMessage { ViewName = "FirstView" });
});
}
}
}
}
SwitchViewMessage.cs
namespace WpfApplication1
{
public class SwitchViewMessage
{
public string ViewName { get; set; }
}
}

Wpf TabControl Interaction.Trigger fires mores than once

I have an unexpected behaviour with a Wpf-Tabcontrol and Dataemplate with Interaction.Trgiggers.
First I define a "ViewModel". It's quite simple:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace WpfApplication3 {
public class Vm: INotifyPropertyChanged {
public Vm() {
this.CmdClick = new RelayCommand( p => this.ExecuteClick(), p => this.CanExecuteClick() );
}
private string myName;
public string MyName {
get { return myName; }
set {
if( myName != value ) {
myName = value;
if( this.PropertyChanged != null ) {
this.PropertyChanged( this, new PropertyChangedEventArgs( "MyName" ) );
}
}
}
}
private RelayCommand cmdClick;
public RelayCommand CmdClick {
get { return cmdClick; }
set { cmdClick = value; }
}
#region Command
private bool CanExecuteClick() {
return true;
}
public void ExecuteClick() {
MessageBox.Show( "MyName is " + MyName );
}
#endregion
public event PropertyChangedEventHandler PropertyChanged;
}
}
Next, I define a Datatemplate:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:l="clr-namespace:WpfApplication3"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate DataType="{x:Type l:Vm}" x:Key="Vm">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBox Text="{Binding Path=MyName}" Grid.Row="0"/>
<i:Interaction.Triggers>
<ei:KeyTrigger Key="F5" ActiveOnFocus="True" FiredOn="KeyUp" >
<i:InvokeCommandAction Command="{Binding CmdClick}" />
</ei:KeyTrigger>
</i:Interaction.Triggers>
</Grid>
</DataTemplate>
</ResourceDictionary>
I use the datatemplate on the mainform inside a TabControl:
<Window x:Class="WpfApplication3.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:l="clr-namespace:WpfApplication3"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Dictionary1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
<TabControl>
<TabItem Header="Tab1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<ContentControl ContentTemplate="{StaticResource Vm}" x:Name="vm11" Content="{Binding}" Grid.Row="0"/>
</Grid>
</TabItem>
<TabItem Header="Tab2">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ContentControl ContentTemplate="{StaticResource Vm}" x:Name="vm21" Content="{Binding}" Grid.Row="0"/>
<ContentControl ContentTemplate="{StaticResource Vm}" x:Name="vm22" Content="{Binding}" Grid.Row="1"/>
</Grid>
</TabItem>
</TabControl>
</Window>
The code behind is simple:
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;
namespace WpfApplication3 {
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
public MainWindow() {
InitializeComponent();
this.vm11.Content = vm1;
this.vm21.Content = vm2;
this.vm22.Content = vm3;
this.vm1.MyName = "Name1";
this.vm2.MyName = "Name2";
this.vm3.MyName = "Name3";
}
Vm vm1 = new Vm();
Vm vm2 = new Vm();
Vm vm3 = new Vm();
}
}
When i run the program, I chlick in the first TextBox, press F5 and the MessageBox posup. Ok.
I switch the tabpage, click inside the second TextBox, press F5 and the MessageBox appears again. OK.
I switch back to the firsz tabpage, press F5 and the MessageBox appears twice. Uuuh. Whatss wrong.
I switch back to the second tabpage,the messagebox appears twice again.
After switching to the first tabpage, the messagebox is displayed treetimes now. And so on.
It is like, the KeyUp-Event is assigned internaly, when the datatemplate is displayed again, without dereferencing it. But ehat can I do ?
I think you need to change this property from
private RelayCommand cmdClick;
public RelayCommand CmdClick {
get { return cmdClick; }
set { cmdClick = value; }
To
private RelayCommand cmdClick;
public RelayCommand CmdClick {
get { return cmdClick; }
set { if(cmdClick == null)cmdClick = value; }

Bind XAML elements to entities TwoWay

I want to bind an entity property (say Salary) to a property of a XAML element (like a TextBox.Text)
and use this binding to save Text of TextBox to salary field which is bound as a entity property to 'Text' of some TextBox.
Something like the following :
<Grid DataContext="Employee">
<TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
</Grid>
you just can bind Properties in xaml - so your salary have to be a property and not a field. if your Employee is the class with the salary you can set datacontext to an instance of it. you can do it in xaml or codebehind or with binding.
public class Employee //implement INotifyPropertyChanged to get the power of binding :)
{
public decimal Salary {get;set}
}
view.xaml
<Grid>
<Grid.DataContext>
<local:Employee/>
</Grid.DataContext>
<TextBox Text="{Binding Path=Salary, Mode=TwoWay}"/>
</Grid>
you can set the datacontext in many ways
XAML Two-Way Binding, 'Windows Universal' style, step-by-step
In Visual Studio 2017, create a Visual C# blank app (Universal Windows). Name it 'MyProject'.
Add a class Employee to it, and then modify boilerplate code as follows:
// Employee.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace MyProject
{
public class Employee : INotifyPropertyChanged
{
private string salary;
public string Salary
{
get
{
return this.salary;
}
set
{
if (value != this.salary)
{
this.salary = value;
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
// This method MUST BE called by the Set accessor of each property for TwoWay binding to work.
// The CallerMemberName attribute that is applied to the optional propertyName
// parameter causes the property name of the caller to be substituted as an argument.
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// Constructor with one parameter
public Employee(string annualSalary) { salary = annualSalary; }
}
}
Notice that class Employee implements the INotifyPropertyChanged Interface.
Add class EmployeeViewModel to project, and modify boilerplate code as follows:
// EmployeeViewModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyProject
{
public class EmployeeViewModel
{
private Employee defaultEmployee = new Employee("50000");
public Employee DefaultEmployee { get { return this.defaultEmployee; } }
}
}
Modify MainPage.xaml.cs boilerplate code as follows
//MainPage.xaml.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace MyProject
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.ViewModel = new EmployeeViewModel();
}
public EmployeeViewModel ViewModel { get; set; }
}
}
Modify MainPage.xaml boilerplate code as follows:
<Page
x:Class="MyProject.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyProject"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" HorizontalAlignment="Center" VerticalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions >
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!--TextBlock will provide visual feedback that the two-way binding is working-->
<TextBlock x:Name="Control" Text="{x:Bind ViewModel.DefaultEmployee.Salary, Mode=OneWay}" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Center"/>
<!--TextBox has two-way binding-->
<TextBox x:Name="Input" Text="{x:Bind ViewModel.DefaultEmployee.Salary, Mode=TwoWay}" Margin="10" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Center"/>
<!--Button does nothing other than allow TextBox to lose focus-->
<Button x:Name="btn1" Content="Hello" Grid.Column="1" Grid.Row="3"
Foreground="Green"
HorizontalAlignment="Center"/>
</Grid>
</Page>
Notice, both 'Input' TextBox and 'Control' TextBlock are bound to the same Salary property of DefaultEmployee. The idea is that you edit and change the salary in the 'Input' TextBox, and then you can visually see the Two-Way binding at work, because the 'Control' TextBlock will update. This happens when the 'Input' TextBox loses focus (it is to allow the change of focus, for instance after pressing TAB key, that the 'Hello' button was added - the button in itself does absolutely nothing).
Build and Run. Modify salary, and either TAB or click button:
No you cant do like that. You cant Set the Class name to the DataContext. It should be the instance of Employee class.

Resources