How to notify viewmodel collection that property on model class has changed - wpf

I have a class that has a boolean property called IsChecked.
A collection of this class exist in my viewmodel. I've bound a datagrid in my view to this collection. I need to call a method in my viewmodel when the checkbox in the view gets changed. I've implemented INotifyPropertyChanged on the class and it is firing when I check the box but I don't know how to call the method in my viewmodel.
Here's the class in my model...
public class AccountComponent : INotifyPropertyChanged
{
public string Name { get; set; }
public decimal Amount { get; set; }
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
NotifyPropertyChanged("IsChecked");
}
}
public bool Enabled { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
Here's the collection in my viewmodel...
private ObservableCollection<AccountComponent> _accountComponents;
private string _accountStatus;
public ObservableCollection<AccountComponent> AccountComponents
{
get { return _accountComponents; }
set
{
_accountComponents = value;
NotifyPropertyChanged("AccountComponents");
CalculateComponentTotal();
}
}
Here's my XAML in the view...
<DataGrid ItemsSource="{Binding AccountComponents}" AutoGenerateColumns="False" Margin="5">
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<CheckBox IsChecked="{Binding IsChecked, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" IsEnabled="{Binding Enabled}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Binding="{Binding Name}" Header="Component" Width="*" IsReadOnly="True" ElementStyle="{DynamicResource TextBlock-Sketch}"/>
<DataGridTextColumn Binding="{Binding Amount,StringFormat={}{0:C}}" IsReadOnly="True" Header="Charge" ElementStyle="{DynamicResource TextBlock-Sketch}">
<DataGridTextColumn.CellStyle>
<Style>
<Setter Property="TextBlock.TextAlignment" Value="Right"/>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>

Since AccountComponent implements INPC you can observe the IsChecked property in your VM.
say in your VM constructor:
AccountComponents = new ObservableCollection<AccountComponent>();
AccountComponents.CollectionChanged += AccountComponentsOnCollectionChanged;
...
private void AccountComponentsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs args) {
if (args.NewItems != null && args.NewItems.Count != 0)
foreach (AccountComponent account in args.NewItems)
account.PropertyChanged += AccountOnPropertyChanged;
if (args.OldItems != null && args.OldItems.Count != 0)
foreach (AccountComponent account in args.OldItems)
account.PropertyChanged -= AccountOnPropertyChanged;
}
private void AccountOnPropertyChanged(object sender, PropertyChangedEventArgs args) {
if (args.PropertyName == "IsChecked")
// Invoke Your VM Function Here
}
That should be it.

In Xaml:
add the following namspace..
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Now for you checkbox add the following code:
<CheckBox>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Checked">
<i:InvokeCommandAction Command="{Binding CheckedCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</CheckBox>
In ViewModel:
public ICommand CheckedCommand
{
get
{
return new DelegateCommand(OnChecked);//Delegate command is the Implemntation of Icommand Interface
}
}
public void OnLogin(object param)
{
//code for you checked event
}
Hope this will help you.

Related

MouseDoubleClick on ListItem with MVVM in WPF

I want to show dialog when i double click any of the list items. But the flow of the program never go in the ShowTextCommand property. I get the list of the names (that works fine) but I can't get the dialog. This is my XAML:
<ListView ItemsSource="{Binding List}" >
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding ShowTextCommand, UpdateSourceTrigger=PropertyChanged}"></MouseBinding>
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
this is my Command class:
public class EnterTextCommand : ICommand
{
public EnterTextCommand(TekstoviViewModel vm)
{
ViewModel = vm;
}
private TekstoviViewModel ViewModel;
#region ICommand interface
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public bool CanExecute(object parameter)
{
return true;
// return ViewModel.CanExecute;
}
public void Execute(object parameter)
{
ViewModel.EnterText();
}
#endregion
}
and the view model
private ICommand command;
public ICommand ShowTextCommand
{
get
{
if (command == null)
command = new EnterTextCommand(this);
return command;
}
internal void EnterText()
{
MessageBox.Show("Event Success");
}
Can someone help ?
Your DataTemplate can't find the command, specify the full path to it using ElementName Binding
<ListView ItemsSource="{Binding List}" x:Name="MainList">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}">
<TextBlock.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick" Command="{Binding DataContext.ShowTextCommand, UpdateSourceTrigger=PropertyChanged,ElementName=MainList}"></MouseBinding>
</TextBlock.InputBindings>
</TextBlock>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>

Checkbox is not checked in DevExpress GridControl using wpf

I am trying to work on DevExpress GridControl Checkbox column but problem is that when I binding the checkbox value in XAML code dynamically its not work perfectlly
below I provide you my demo project code :-
XAML Code:-
<dxg:GridControl AutoPopulateColumns="True" HorizontalAlignment="Left" Margin="0,40,0,0" Name="gridControl1" VerticalAlignment="Top" Height="318" Width="503">
<dxg:GridControl.View>
<dxg:TableView Name="tableView1" ShowTotalSummary="True" />
</dxg:GridControl.View>
<dxg:GridControl.Columns>
<dxg:GridColumn DisplayMemberBinding="{Binding Path=EvenOdd}" Header="Even/Odd" />
<dxg:GridColumn Name="PickColumn" Header="Pick" Width="30"
AllowColumnFiltering="False" AllowSorting="False">
<dxg:GridColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Path=IsValid}"
HorizontalAlignment="Center" VerticalAlignment="Center" >
</CheckBox>
</DataTemplate>
</dxg:GridColumn.CellTemplate>
</dxg:GridColumn>
</dxg:GridControl.Columns>
</dxg:GridControl>
my cs file code:-
public class ss
{
public bool IsValid { get; set; }
public string EvenOdd { get; set; }
}
Code Behind:
public List<ss> sList = new List<ss>();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0)
{
sList.Add(new ss { IsValid = true, EvenOdd = "Even" });
}
else
{
sList.Add(new ss { IsValid = false, EvenOdd = "Odd" });
}
}
gridControl1.ItemsSource = sList;
}
Adding on to HighCore's answer. If you would like to edit the data in your grid.
See ColumnBase.CellTemplate Property:
To enable data editing, use an editor shipped with the DevExpress Data Editors Library for WPF. The editor's Name must be set to
'PART_Editor'.
Standard controls can be used in CellTemplate only for display purposes. Data editing is not allowed.
Then,
xmlns:dxe="http://schemas.devexpress.com/winfx/2008/xaml/editors"
<dxg:GridColumn Name="PickColumn"
Header="Pick"
Width="30"
AllowColumnFiltering="False"
AllowSorting="False">
<dxg:GridColumn.CellTemplate>
<DataTemplate>
<dxe:CheckEdit x:Name="PART_Editor"
EditValue="{Binding Path=Data.IsValid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</dxg:GridColumn.CellTemplate>
</dxg:GridColumn>
You still need to use HighCore's implementation of INotifyPropertyChanged.
First of all you need to correct the binding inside the CellTemplate:
<CheckBox IsChecked="{Binding Path=RowData.Row.IsValid}"/>
Second, your data items should implement INotifyPropertyChanged:
public class ss:INotifyPropertyChanged
{
private bool _isValid;
private string _evenOdd;
public bool IsValid
{
get { return _isValid; }
set
{
_isValid = value;
OnPropertyChanged("IsValid");
}
}
public string EvenOdd
{
get { return _evenOdd; }
set
{
_evenOdd = value;
OnPropertyChanged("EvenOdd");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
xmlns:dxgcore="http://schemas.devexpress.com/winfx/2008/xaml/grid"
<dxgcore:GridColumn Width="20"
AllowEditing="True"
Binding="{Binding Path=IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Header="R"
Visible="{Binding CheckboxSelection}"
VisibleIndex="6">
<dxgcore:GridColumn.CellTemplate>
<DataTemplate>
<dxe:CheckEdit HorizontalAlignment="Center"
VerticalAlignment="Center"
Command="{Binding
Path=View.DataContext.IsCheckedCommand}"
CommandParameter="{Binding RowData.Row}"
IsChecked="{Binding RowData.Row.IsChecked, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding Path=View.DataContext.IsCheckBoxEnabled, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</dxgcore:GridColumn.CellTemplate>
</dxgcore:GridColumn>
And Notifychanged property
private bool _isChecked;
public bool IsChecked
{
get { return _isChecked; }
set
{
_isChecked = value;
RaisePropertyChanged("IsChecked");
}
}

WPF: How to use Style.Triggers

I want to implement (file) Explorer like icon display. The items have date and label.
User should be able to edit the label:
Select an item
Click on label
Label's TextBlock is replaced with TextBox for editing
How to end editing (just for info):
Click anywhere outside of the TextBox
Press Enter keyboard key (by implementing ICommand?)
1st I tried to set the Visibility of TextBlock and TextBox in code found out it is not the 'right' way to to do. Maybe it is possible to edit item's Label using (Data)Triggers?
I can track the OnClickLabelBlock and set selectedMedia.IsEditing = true; but it does not fire the trigger.
Any idea why MediaItem.IsEditing property value change is notifying the DataTrigger? Is it something to do with the order of execution or priority mechanism?
I will pick the answer which guides me to the 'best' architecture to solve it.
Thanks.
XAML:
<Window x:Class="WPFComponents.DailyImages"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Model="clr-namespace:WPFComponents.Model"
Title="Media Items" Height="300" Width="300">
<ListView x:Name="_mediaItemList" ItemsSource="{Binding MediaItems}"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}" />
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemTemplate>
<DataTemplate DataType="Model:MediaItem">
<Grid Width="80" Margin="4">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Image HorizontalAlignment="Center" Stretch="Uniform" Source="{Binding Path=IconPath}" Width="70" />
<StackPanel Grid.Row="2">
<TextBlock Text="{Binding Path=Date}" TextWrapping="Wrap" />
<TextBlock x:Name="_labelTextBlock" Text="{Binding Path=Label}" TextWrapping="Wrap"
PreviewMouseLeftButtonDown="OnClickLabelBlock">
</TextBlock>
<TextBox x:Name="_labelTextBox" Text="{Binding Path=Label}" Visibility="Collapsed"
TextWrapping="WrapWithOverflow" TextAlignment="Center">
</TextBox>
</StackPanel>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsEditing}" Value="True">
<Setter TargetName="_labelTextBlock" Property="Visibility" Value="Collapsed" />
<Setter TargetName="_labelTextBox" Property="Visibility" Value="Visible" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" VerticalAlignment="Top" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
Source:
public partial class DailyImages
{
public DailyImages()
{
InitializeComponent();
ViewModel.DailyImages dailyImages = new ViewModel.DailyImages();
// DailyImages has ObservableCollection<MediaItem> MediaItems property
_mediaItemList.DataContext = dailyImages;
}
private void OnClickLabelBlock(object sender, MouseButtonEventArgs e)
{
TextBlock notes = sender as TextBlock;
if (notes == null)
return;
MediaItem selectedMedia = notes.DataContext as MediaItem;
if (selectedMedia == null)
{
// TODO: Throw exception
return;
}
_mediaItemList.SelectedItems.Clear();
selectedMedia.IsSelected = true;
selectedMedia.IsEditing = true;
}
public class MediaItem
{
public MediaItem()
{
IsEditing = false;
IsSelected = false;
}
public DateTime Date { get; set; }
public string Label { get; set; }
public string IconPath { get; set; }
public bool IsEditing { get; set; }
public bool IsSelected { get; set; }
}
References:
Dependency Property Value Precedence
Part II: ListView & File Explorer Like Behaviour
MediaItem must implement INotifyPropertyChanged and each of its properties that must be bound, must call RaisePropertyChanged in order for the binding to work correctly. In your case, the Binding on IsEditing has no way to know that the value has changed.
To bind your IsEditing property, WPF has to be notified when it is modified.
Then you have to implement INotifyPropertyChanged in MediaItem. (Or add dependency properties)
public class MediaItem : INotifyPropertyChanged
{
public MediaItem()
{
IsEditing = false;
IsSelected = false;
}
// Use the same pattern for Date, Label & IconPath if these value may change after the MediaItem instance has been added to the collection MediaItems.
public DateTime Date { get; set; }
public string Label { get; set; }
public string IconPath { get; set; }
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private bool isEditing;
public bool IsEditing
{
get { return isEditing; }
set
{
if (isEditing != value)
{
isEditing = value;
OnPropertyChanged("IsEditing");
}
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Otherwise, your code is correct.

WPF DataGrid ComboBox causes InvalidOperationException

I am getting an InvalidOperationException('DeferRefresh' is not allowed during an AddNew or EditItem transaction.) from my datagrid when I try to edit the value of a combo box column. The items I am showing all have a reference to one other item in the same list so this is what I am using the combobox for. It is bound to the same collection as the datagrid is. My application I am working on is targetting .NET 3.5, but I have put together an example that is exactly the same in .NET 4 since the datagrid is built in. Here is the code for items in the datagrid:
public class TestItem : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private int m_ID;
private string m_Name;
private int m_OppositeID;
public int ID
{
get { return m_ID; }
set
{
m_ID = value;
RaisePropertyChanged("ID");
}
}
public string Name
{
get { return m_Name; }
set
{
m_Name = value;
RaisePropertyChanged("Name");
}
}
public int OppositeID
{
get { return m_OppositeID; }
set
{
m_OppositeID = value;
RaisePropertyChanged("OppositeID");
}
}
public TestItem(int id, string name, int oppID)
{
ID = id;
Name = name;
OppositeID = oppID;
}
}
This is the code in my window:
public partial class MainWindow : Window, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ObservableCollection<TestItem> m_Items;
public ObservableCollection<TestItem> Items
{
get { return m_Items; }
set
{
m_Items = value;
RaisePropertyChanged("Items");
}
}
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
Items = new ObservableCollection<TestItem>();
Items.Add(new TestItem(0, "Fixed", 0));
Items.Add(new TestItem(1, "Left Side", 2));
Items.Add(new TestItem(2, "Right Side", 1));
}
}
and finally my xaml:
<Window x:Class="DataGrid_Combo_Test.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">
<Grid>
<DataGrid ItemsSource="{Binding Path=Items}" AutoGenerateColumns="False">
<DataGrid.Resources>
<Style x:Key="ItemsSourceStyle" TargetType="ComboBox">
<Setter Property="ItemsSource" Value="{Binding Path=DataContext.Items, RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=ID}" Header="ID" Width="*"/>
<DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" Width="*"/>
<DataGridComboBoxColumn Header="Opposite Item" Width="*" DisplayMemberPath="Name" SelectedValuePath="ID" SelectedValueBinding="{Binding Path=OppositeID}" ElementStyle="{StaticResource ItemsSourceStyle}" EditingElementStyle="{StaticResource ItemsSourceStyle}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Thanks in advance for any assistance you can offer!
I found out how to fix this issue.
I created a CollectionViewSource like this in my Window.Resources:
<Window.Resources>
<CollectionViewSource x:Key="itemSource" Source="{Binding Path=Items}"/>
</Window.Resources>
Then changed my combobox column definition to the following:
<DataGridComboBoxColumn Header="Opposite Item" Width="*" DisplayMemberPath="Name" SelectedValuePath="ID" SelectedValueBinding="{Binding Path=OppositeID}" ItemsSource="{Binding Source={StaticResource itemSource}}"/>
Try following sequence before calling Refersh on CollectionView or DataGridXYZ.Items
DataGridX.CommitEdit();
DataGridX.CancelEdit();
Worked for me.

Changing the User Control of Window dynamically in WPF (MVVM)

I am working on wpf mvvm pattern.
I have a user control in which i am loading a list of checkboxes in DataGridCheckBoxColumn and binding it to IsSelected property from my viewmodel.
Tha xaml code is like this:
<DataGrid Width="150" Grid.Row="0" Background="LightGray" CanUserAddRows="False" AutoGenerateColumns="False" HorizontalAlignment="Left" Name="dataGridCustomers" ItemsSource="{Binding Path=UsecaseListItems}" CanUserResizeColumns="False" CanUserResizeRows="False">
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding Path=IsSelected,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay,IsAsync=True}" Width="50">
<DataGridCheckBoxColumn.HeaderTemplate>
<DataTemplate x:Name="dtAllChkBx">
<CheckBox Name="cbxAll" FontWeight="Bold" Content="All" IsChecked="{Binding Path=DataContext.AllSelected,RelativeSource={RelativeSource AncestorType=UserControl },Mode=TwoWay}"/>
</DataTemplate>
</DataGridCheckBoxColumn.HeaderTemplate>
</DataGridCheckBoxColumn>
<DataGridTextColumn Width="85" Binding="{Binding Path=UsecaseName}" Header="UsecaseName" IsReadOnly="True" >
<DataGridColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="Black"></Setter>
</Style>
</DataGridColumn.HeaderStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
My HomeViewModel is like this:
private bool _IsSelected;
public bool IsSelected
{
get { return _IsSelected; }
set
{
_IsSelected = value;
OnPropertyChanged("IsSelected");
}
}
private Control _someUserControl;
public Control CCS01
{
get { return _someUserControl; }
set { _someUserControl = value; }
}
private UserControl _content;
internal void SetNewContent(UserControl _content)
{
ContentWindow = _content;
}
public UserControl ContentWindow
{
get { return _content; }
set
{
_content = value;
OnPropertyChanged("ContentWindow");
}
}
For my 1st checkbox (CCS01), I have created a view(CCS01.xaml) which contains a few labels and textboxes in grid format.And its corresponding ViewModel is below:
public class CCS01ViewModel: BaseNotifyPropertyChanged
{
HomeViewModel _homeViewModel;
public ICommand OpenUsersCommand { get; private set; }
public CCS01ViewModel(HomeViewModel mainModel)
{
this._homeViewModel = mainModel;
//this._model = model;
OpenUsersCommand = new RelayCommand(OpenUsers, CanOpenUsers);
}
private void OpenUsers(object _param)
{
//UsersPanelViewModel upmodel = new UsersPanelViewModel(_mainModel, _model);
//UsersPanel up = new UsersPanel();
//up.DataContext = upmodel;
//_mainModel.SetNewContent(up);
}
private bool CanOpenUsers(object _param)
{
return true;
}
}
I want to load the selected checkbox view in the main UserControl(ExecutionDetails.xaml) . Currently, I am loading it with the first Checkbox view in it by default like this:
<StackPanel>
<Grid Name="HostGrid">
<ContentControl Content="{Binding ContentWindow}"/>
</Grid>
</StackPanel>
Please suggest me how to bind the view with respective checkboxes user controls dynamically based on the checkbox selection.
The code behind of this(ExecutionDetails.xaml.cs) is like this:
public partial class ExecutionDetails : UserControl
{
public ExecutionDetails()
{
InitializeComponent();
HomeViewModel viewmodel = new HomeViewModel();
CCS01ViewModel ccViewModel = new CCS01ViewModel(viewmodel);
CCS01 obj = new CCS01();
obj.DataContext = ccViewModel;
viewmodel.ContentWindow = obj;
this.DataContext = viewmodel;
}
}

Resources