How to setup / use WPF use-controls with parameters? - c#

There in my mainwindow.xaml I've got the grid with:
<CustomControl:GridControl ShowCustomGridLines="True" Grid.Column="2" Grid.Row="0">
<local:_13cap/>
</CustomControl:GridControl>
Where 13cap is my custom control:
<UserControl x:Class="TTTP._13cap"
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:CustomControl="clr-namespace:WpfApplication1.CustomControl"
mc:Ignorable="d">
<CustomControl:GridControl ShowCustomGridLines="True">
<Grid.ColumnDefinitions>
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.ColumnSpan="3" Grid.Row="0" HorizontalAlignment="Center" VerticalAlignment="Center" Text="ВСЕГО" />
<CustomControl:GridControl ShowCustomGridLines="True" Grid.Column="2" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="1" Text="П" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Grid.Column="1" Grid.Row="1" Text="Ф" HorizontalAlignment="Center" VerticalAlignment="Center" />
<TextBlock Grid.Column="2" Grid.Row="1" Text="%" HorizontalAlignment="Center" VerticalAlignment="Center" />
</CustomControl:GridControl>
</CustomControl:GridControl>
</UserControl>
But I want to call it with only one different text parameter ( Text="ВСЕГО" ) alike I want to call <local:_13cap MyText="CustomText"/> to override "ВСЕГО". How can I create UserControl with such parameter in it?

Implement a DependancyProperty that you can change from code-behind and bind to in XAML.
Code behind:
public class MyUserControl : UserControl, INotifyPropertyChanged
{
//INotifyPropertyChanged implementation
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
//The XAML binding uses this
public static readonly DependencyProperty CaptionProperty =
DependencyProperty.Register("Caption", typeof(string), typeof(MyUserControl),
new PropertyMetadata(string.Empty, OnCaptionPropertyChanged));
//Your code-behind uses this
public string Caption
{
get { return GetValue(CaptionProperty).ToString(); }
set
{
SetValue(CaptionProperty, value);
OnPropertyChanged("Caption");
}
}
Xaml:
<UserControl (...)>
<Grid>
<Label x:Name="labCaption" Content="{Binding Caption}"/>
</Grid>
</UserControl>
There are lots of other questions here about this and lots of good articles and tutorial on google that explain it all better then I could.

Related

How can I hide rows in a DataGrid?

I am trying to create a "notes" app using wpf mvvm. I have a MainWindow containing a DataGrid with data that is bound to an ObservableCollection. In MainWindowView I have a "Find" button which calls FindWindowDialog. In the FindWindowDialog in the textbox, I must enter the text that will be searched and click "Find", after which the DataGrid MainWindowView should hide those lines whose content does not contain the searched text. I don't really know how to do this, after 2 days of searching I decided to ask a question. I googled on this topic and I have a suggestion that I should delve into the messenger pattern and converters
MainWindow.xaml(View)
<Window x:Class="NotesARK6.View.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:NotesARK6.View"
xmlns:model="clr-namespace:NotesARK6.Model"
xmlns:viewmodel="clr-namespace:NotesARK6.ViewModel"
mc:Ignorable="d"
Title="Notes" Height="450" Width="800"
x:Name="_mainWindow"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="1*"/>
<RowDefinition Height="10*"/>
<RowDefinition Height="20"/>
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding NotesCollection}" SelectedItem="{Binding SelectedNote}" IsReadOnly="True" AutoGenerateColumns="False" x:Name="DataGrid_Notes" Margin="5" Grid.Row="2" Grid.Column="1">
<DataGrid.InputBindings>
<MouseBinding Gesture="LeftDoubleClick" Command="{Binding EditNoteCommand}" CommandParameter="{Binding SelectedNote}" />
</DataGrid.InputBindings>
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="1*" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Content" Width="3*" Binding="{Binding Content}"/>
</DataGrid.Columns>
</DataGrid>
<ToolBar Grid.Row="1" Grid.Column="1" Margin="5">
<Button Content="Create" Command="{Binding CreateNewNoteCommand}"/>
<Separator />
<Button Content="Delete" Command="{Binding DeleteNoteCommand}" CommandParameter="{Binding SelectedNote}"/>
<Separator />
<Button Content="Find" Command="{Binding FindNoteCommand}"/>
</ToolBar>
</Grid>
</Window>
FindWindowDialog.xaml(view)
<Window x:Class="NotesARK6.ViewModel.Dialogs.FindWindowDialog"
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:NotesARK6.ViewModel.Dialogs"
mc:Ignorable="d"
Title="Find" Height="250" Width="400"
WindowStartupLocation="CenterScreen"
Topmost="True">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="35"/>
<RowDefinition Height="60"/>
<RowDefinition Height="50"/>
<RowDefinition Height="90"/>
</Grid.RowDefinitions>
<Grid Grid.Row="1" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding SearchByName}" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5" Content="Search by name" Grid.Column="0"></CheckBox>
<CheckBox IsChecked="{Binding SearchByContent}" VerticalAlignment="Center" HorizontalAlignment="Center" Margin="5" Content="Search by content" Grid.Column="1"></CheckBox>
</Grid>
<TextBox Text="{Binding SearchString}" Margin="5" Grid.Row="2" Grid.Column="1"/>
<Button Command="{Binding FindNotesCommand}" Margin="5" Content="Find" Grid.Row="3" Grid.Column="1" />
</Grid>
</Window>
FindWindowDialogViewModel.cs
public class FindWindowDialogViewModel : INotifyPropertyChanged
{
private string searchString;
private bool searchByName;
private bool searchByContent;
//Controll Commands
public ControllComands FindNotesCommand { get; private set; }
//Controll Commands
public FindWindowDialogViewModel()
{
FindNotesCommand = new ControllComands(FindNote);
}
public string SearchString
{
get
{
return searchString;
}
set
{
searchString = value;
OnPropertyChanged();
}
}
public bool SearchByName
{
get
{
return searchByName;
}
set
{
searchByName = value;
OnPropertyChanged("SearchByName");
}
}
public bool SearchByContent
{
get
{
return searchByContent;
}
set
{
searchByContent = value;
OnPropertyChanged("SearchByContent");
}
}
public void FindNote()
{
MessageBox.Show(SearchByName.ToString() + " " + SearchByContent.ToString());
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string prop = "")
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(prop));
}
}
How can I use the command contained in FindWindowDialogViewModel to hide rows in the DataGrid MainWindowView ?
I would like something like this: (this is pseudocode)
public void FindNote()
{
foreach(var row in MainWindow.DataGrid.Rows)
{
string searchingText = FindNoteDialog.TextBox.Text;
if (!row.Content.Contains(searchingText))
{
row.Visibillity = false;
}
}
}
For this purpose collections provide filtering via their views (see Binding to collections and CollectionView API remarks to learn more).
Filtering using the collection's view has much better performance than hiding rows or removing items from the original collection.
To do so, you must get the ICollectionView of the source collection
Note.cs
class Note
{
public string Summary { get; set; }
public DateTime Timestamp { get; set; }
}
ViewModel.cs
class ViewModel : INotifyPropertyChanged
{
public ObservableCollection<Note> Notes { get; }
public string SearchKey { get; set; }
public ICommand FilterNotesCommand => new RelayCommand(ExecuteFilterNotes);
private void ExecuteFilterCommands(object commandParameter)
{
ICollectionView notesView = CollectionViewSource.GetDefaultView(this.Notes);
notesView.Filter = item => (item as Note).Summary.Contains(this.SearchKey);
}
}
MainWindow.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<StackPanel>
<TextBox Text="{Binding SearchKey}" />
<Button Command="{Binding FilterNotesCommand}" Content="Filter Table" />
<DataGrid ItemsSource="{Binding Notes}" />
</StackPanel>
</Window>

How to get my View set in the Content Presenter

I'm currently working on a database-based application for work and I am struggling with connecting the ViewModel methods to my view. Here is what I've got so far:
public class MainViewModel : BaseViewModel
{
public ICommand SwitchViewsCommand { get; private set; }
public MainViewModel()
{
SwitchViewsCommand = new RelayCommand((parameter) => CurrentView = (UserControl)Activator.CreateInstance(parameter as Type));
}
private UserControl _currentView;
public UserControl CurrentView
{
get
{
return _currentView;
}
set
{
if (value != _currentView)
{
_currentView = value;
OnPropertyChanged("CurrentView");
}
}
}
}
This is my MainViewModel and following my Xaml-Code
<Window x:Class="sKillPase.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodels="clr-namespace:sKillPase.Core.ViewModels;assembly=sKillPase.Core" xmlns:view="clr-namespace:sKillPase.View"
xmlns:local="clr-namespace:sKillPase.View"
d:DataContext="{d:DesignInstance Type=viewmodels:MainViewModel}"
mc:Ignorable="d"
Title="MainWindow" Height="800" Width="1200">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="80" />
<RowDefinition Height="*" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Border x:Name="Top" Grid.Column="0" Grid.ColumnSpan="2" Background="Black" ></Border>
<Border x:Name="Buttons" Grid.Row="1" Grid.RowSpan="2" Background="Black"></Border>
<Border x:Name="Content" Grid.Row="1" Grid.Column="1" Background="#FF303030"></Border>
<Border x:Name="Bottom" Grid.Row="2" Grid.Column="1" Background="Black"/>
<ContentPresenter Grid.Row="1" Grid.Column="1" x:Name="ContentArea" Content="{Binding CurrentView}"/>
<StackPanel x:Name="ButtonPanel" Margin="5" Grid.Row="1">
<Button x:Name="Data"
Command="{Binding SwitchViewsCommand }"
CommandParameter="{x:Type local:DataView}"
>
Daten bearbeiten
</Button>
<Button x:Name="Report"
Command="{Binding SwitchViewsCommand}"
CommandParameter="{x:Type viewmodels:ReportViewModel}"
>
Report erstellen
</Button>
</StackPanel>
</Grid>
So my problem is, that if I compile the application, the Content Presenter doesn't show anything. It stays completely empty. So what can I do to add the different views (which I declared as User Controls) to my Content Presenter, by pressing one of the two buttons?
Furthermore, one of the views contains a data grid that shows the different tables of my database. So if I have to watch out for some problems regarding the database, please feel free to state.
Thanks in advance :)

UWP listview doesn't update after updating/adding an element to the MVVM collection list

I am frustrated with the listview ItemSource and MVVM binding. I am binding the listview with a data model. After loading the listview, I add another item to the listview, the update is not reflected in listview, but it shows that the number of items in the list collection is increased by one. If I add the add in the list collection in the constructor, it is shown in the listview.
XAML
<Page
x:Class="App20.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App20"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<Page.DataContext>
<local:VictimsController></local:VictimsController>
</Page.DataContext>
<Grid Padding="10">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<TextBlock Text="List of Victims/Trapped" HorizontalAlignment="Center" Style="{StaticResource HeaderTextBlockStyle}"/>
</Grid>
<Grid Grid.Row="1">
<ListView x:Name="ls" ItemsSource="{Binding VictimList, Mode=TwoWay}">
<ListView.HeaderTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock FontWeight="Bold" HorizontalAlignment="Center" Grid.Column="0" Text="GPSLatitute" />
<TextBlock FontWeight="Bold" HorizontalAlignment="Center" Grid.Column="1" Text="GPSLongtitude" />
<TextBlock FontWeight="Bold" HorizontalAlignment="Center" Grid.Column="2" Text="Date" />
</Grid>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock HorizontalAlignment="Center" Grid.Column="0" Text="{Binding GPSLatitute}" />
<TextBlock HorizontalAlignment="Center" Grid.Column="1" Text="{Binding GPSLongtitude}" />
<TextBlock HorizontalAlignment="Center" Grid.Column="2" Text="{Binding Date}" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Grid>
<Button Content="Publish" VerticalAlignment="Top"
Height="76" Width="114" Click="Publish_Click" />
</Grid>
Controller
public class VictimsController : INotifyPropertyChanged
{
List<VictimProfile> _victims = new List<VictimProfile>();
public VictimsController()
{
//Victims.Add(new VictimProfile() { GPSLatitute = 123, GPSLongtitude = 2333 });
}
public List<VictimProfile> VictimList
{
get
{
return _victims;
}
set
{
_victims = value;
OnPropertyChanged("VictimList");
}
}
public void addVictim(VictimProfile profile)
{
_victims.Add(profile);
OnPropertyChanged("VictimList");
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Adding one item to the listview model or collection
async void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
//convert the message to json format
var payLoad = JsonConvert.DeserializeObject<VictimProfile>(ReceivedMessage);
// we need this construction because the receiving code in the library and the UI with textbox run on different threads
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
txt.Text += ReceivedMessage;
VictimsController model = this.DataContext as VictimsController;
model.addVictim(payLoad); //add item to the list collection
Debug.WriteLine("count: " + ls.Items.Count); //this shows that listview has one more item added to it, but nothing is shown in the listview
//ls.Items.Add(payLoad);
});
}
The point is the list collection has the new item and the ls (listview) also has the item, but it is not shown in the listview.
Finally I solved it.
Changing the list to observable collection has solved the problem.
ObservableCollection<VictimProfile> _victims = new ObservableCollection<VictimProfile>();

Setting position of ItemsControl item

I have a command in my viewmodel that, when executed, will add an item to an observablecollection. In my view, an ItemsControl has its source bound to this collection. So whenever an item is added, a combobox and a textblock will appear for each item.
What I'm trying to do is, have each set of combobox/textblock appear to the right of the last set, until it reaches the end of window, and then the next set will appear below the first, and so on. Was planning to put this in a ScrollViewer. Everything I've tried so far keeps placing each set under the last one, instead of to the right.
Here's my simple model class:
public class DataModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private double _gridColumn;
public double GridColumn
{
get { return _gridColumn; }
set { _gridColumn = value; OnPropertyChanged("GridColumn"); }
}
// Create the OnPropertyChanged method to raise the event
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
Here's the relevant parts of the viewmodel:
public class MainWindowViewModel : INotifyPropertyChanged
{
private int columnNum = 0;
private ObservableCollection<DataModel> _dataModelCollection = new ObservableCollection<DataModel>();
public ObservableCollection<DataModel> DataModelCollection
{
get { return _dataModelCollection; }
set { _dataModelCollection = value; OnPropertyChanged("DataModelCollection"); }
}
public void AddDataModel(object parameter)
{
DataModelCollection.Add(new DataModel {GridColumn = columnNum % 8 });
columnNum += 2;
}
}
And now my view:
<Grid Background="#44D3D3D3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
<ColumnDefinition Width="140*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="46*" />
<RowDefinition Height="139*" />
<RowDefinition Height="38*" />
<RowDefinition Height="78*" />
<RowDefinition Height="60*" />
<RowDefinition Height="50*" />
</Grid.RowDefinitions>
<Button Grid.Row="3"
Grid.Column="2"
Content="Add Set"
Command="{Binding AddDataModelCmd}"/>
<ItemsControl Grid.Row="4"
Grid.RowSpan="2"
Grid.ColumnSpan="9"
ItemsSource="{Binding DataModelCollection}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Grid.Column="{Binding GridColumn}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140*" />
<ColumnDefinition Width="7*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="7" />
<RowDefinition Height="53" />
<RowDefinition Height="50" />
</Grid.RowDefinitions>
<ComboBox Grid.Column="0" Grid.Row="1" />
<TextBlock Text="tester"
Grid.Column="0"
Grid.Row="2"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
I've messed around with setting the ItemsPanelTemplate as a WrapPanel which gave me the side by side result, but I couldn't get any spacing between each set of items.

PropertyChanged is always null in ViewModelBase

I made a simple example to better understan the MVVM pattern.
Here is a link to the sample solution, because its difficult to explain the whole problem:
http://www.2shared.com/file/jOOAnacd/MVVMTestMyCopy.html
There is Employee model (with Age property) and EmployeeViewModel, which contains Employee object and changes its Age property in the following code:
public int Age
{
get { return _employee.Age; }
set
{
if (value == _employee.Age)
return;
_employee.Age = value;
NotifyPropertyChanged("Age");
}
}
EmployeeViewModel is inherited from ViewModelBase class with standard INotifyPropertyCHanged code:
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
I'm trying to change employee's age using ICommand:
public void Increase()
{
this.SelectedEmployee.Age++;
NotifyPropertyChanged("Age");
}
The property is changed, but the binded TextBLock does not change its value.
I checked and saw that NotifyPropertyChanged is called, but PropertyChanged is null.
I also ensured that I have only one PeopleViewModel in my app.
So, why is the PropertyChanged is null?
EDIT:
Here is full code for ViewModelBase:
public class ViewModelBase
{
public String DisplayName { get; set; }
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
#endregion
}
There is PeopleViewModel which contains ObservalbleCollection with EmployeeViewModels and set as DataContext.
The values of properties are changed, but the changes are not shown without reloading objects.
Here is the PeopleViewer.xaml that shows the binding:
<UserControl x:Class="MVVMTestMyCopy.View.PeopleViewer"
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:vm="clr-namespace:MVVMTestMyCopy.ViewModel"
mc:Ignorable="d"
d:DesignHeight="316" d:DesignWidth="410">
<UserControl.Resources>
<vm:PeopleViewModel x:Key="viewModel"/>
</UserControl.Resources>
<Grid DataContext="{Binding Source={StaticResource viewModel}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListBox ItemsSource="{Binding People}"
Grid.Column="0"
Margin="5,5,4,5"
SelectedItem="{Binding SelectedEmployee, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="2"
Text="{Binding FirstName}" />
<TextBlock Margin="2"
Text="{Binding LastName}" />
<TextBlock Margin="0 2"
Text="[" />
<TextBlock Margin="2"
Text="{Binding Age}" />
<TextBlock Margin="0 2"
Text="]" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Grid Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="0.75*" />
<RowDefinition Height="0.25*" />
</Grid.RowDefinitions>
<Grid x:Name="EmployeeDetails"
Grid.Row="0"
DataContext="{Binding SelectedEmployee}"
Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
<RowDefinition Height="1*" />
</Grid.RowDefinitions>
<TextBlock Text="{Binding FirstName}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.Column="0"/>
<TextBlock Text="{Binding LastName}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.Row="1" />
<TextBlock Text="{Binding Age}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Grid.Row="2" />
</Grid>
<StackPanel Orientation="Vertical"
HorizontalAlignment="Center"
Grid.Row="1">
<Button x:Name="button"
Content="-"
Width="32"
Height="32"
Command="{Binding DecreaseCommand}">
</Button>
<Button x:Name="button1"
Content="+"
Width="32"
Height="32"
Command="{Binding IncreaseCommand}">
</Button>
</StackPanel>
</Grid>
</Grid>
</UserControl>
In your project, you don't actually implement INotifyPropertyChanged on your view-model. You have:
public class ViewModelBase
But this should be:
public class ViewModelBase : INotifyPropertyChanged
Because you don't implement INotifyPropertyChange, the WPF binding system will not be able to add a handler for your PropertyChanged event.
Implement the INotifyPropertyChanged interface on your ViewModelBase.
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx
You have defined a PropertyChanged event but it is the interface that is important.
I checked you application using MVVM-Light instead of your BaseViewModel implementation and it worked as it should.
I suggest using MVVM-Light because of other features like Messaging, Disposing and Blendability.
You can easily download and install it using NuGet.
If you want to implement INotifyPropertyChange anyway, here is code that will do it:
public class MainViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}

Categories

Resources