what to use besides OnCurrentChanged since it is not firing WPF MVVM - wpf

I have a combobox with 2 date pickers on my main xaml file
<ComboBox Margin="5" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="90"
x:Name="datOpt"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=dateOptObj.dates}"
Background="{x:Null}" />
<DatePicker Padding="5,5,5,5"
Text="{Binding Path=dateOptObj.openDate, Mode=TwoWay}"/>
<TextBlock Padding="5,5,5,5" Text=" to "/>
<DatePicker Padding="5,5,5,5"
Text="{Binding Path=dateOptObj.closeDate, Mode=TwoWay}" />
in the viewmodel I create an instance like this
public mdDateOptions dateOptObj { get; set; }
public vwMain()
{
try
{
// Initialize the panel switches
dateOptObj = new mdDateOptions();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
the class of mdDateOptions is as follows
class mdDateOptions : vwBase
{
private DateTime _openDate;
public DateTime openDate
{
get
{
return _openDate;
}
set
{
if (_openDate != value)
{
_openDate = value;
RaisePropertyChanged("openDate");
}
}
}
private DateTime _closeDate;
public DateTime closeDate
{
get
{
return _closeDate;
}
set
{
if (_closeDate != value)
{
_closeDate = value;
RaisePropertyChanged("closeDate");
}
}
}
private DateTime _openDatePrevious;
public DateTime openDatePrevious
{
get
{
return _openDatePrevious;
}
set
{
if (_openDatePrevious != value)
{
_openDatePrevious = value;
RaisePropertyChanged("openDatePrevious");
}
}
}
private DateTime _closeDatePrevious;
public DateTime closeDatePrevious
{
get
{
return _closeDatePrevious;
}
set
{
if (_closeDatePrevious != value)
{
_closeDatePrevious = value;
RaisePropertyChanged("closeDatePrevious");
}
}
}
private ICollectionView _datOpts;
public ObservableCollection<string> dates { get; private set; }
public ICollectionView datesView
{
get
{
return _datOpts;
}
}
public mdDateOptions()
{
dates = new ObservableCollection<string>();
dates.Add("Rolling Year");
dates.Add("Year to Date");
dates.Add("Last Year");
_datOpts = CollectionViewSource.GetDefaultView(dates);
_datOpts.CurrentChanged += new EventHandler(OnCurrentChanged);
}
public mdDateOptions(Boolean value)
{
dates = new ObservableCollection<string>();
dates.Add("Rolling Year");
dates.Add("Year to Date");
dates.Add("Last Year");
_datOpts = CollectionViewSource.GetDefaultView(dates);
_datOpts.CollectionChanged += this.OnCurrentChanged;
}
public void OnCurrentChanged(object sender, EventArgs e)
{
string currSel = (string)_datOpts.CurrentItem;
DateTime p_date = new DateTime();
p_date = DateTime.Today;
switch (currSel)
{
case "Rolling Year":
openDate = DateTime.Today.AddYears(-1);
closeDate = DateTime.Today;
openDatePrevious = DateTime.Today.AddYears(-2);
closeDatePrevious = DateTime.Today.AddYears(-1);
break;
case "Year to Date":
openDate = new DateTime(DateTime.Today.Year, 1, 1);
closeDate = DateTime.Today;
openDatePrevious = new DateTime(DateTime.Today.AddYears(-1).Year, 1, 1);
closeDatePrevious = DateTime.Today.AddYears(-1);
break;
case "Last Year":
openDate = new DateTime(DateTime.Today.AddYears(-1).Year, 1, 1);
closeDate = new DateTime(DateTime.Today.AddYears(-1).Year, 12, 31);
openDatePrevious = new DateTime(DateTime.Today.AddYears(-2).Year, 1, 1);
closeDatePrevious = new DateTime(DateTime.Today.AddYears(-2).Year, 12, 31);
break;
default:
MessageBox.Show("Unknown Date Option");
break;
}
}
}
When the program first loads it goes into the OncurrentChanged and loads the appropriate dates. But after when i am clicking a button in a userControl on the same main xaml file the dateOptObj is null and when I try to create a new instance of the mdDateOptions it doesnt trigger the onCurrentChanged because nothing has changed! My question how can I get my dateOptObj to contain the proper dates when clicking my button in the userControl on the main xaml file. Thanks in advance!
This is the main Xaml file
<Window x:Class="ManagementDashboard.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:ManagementDashboard"
Title="Dashboard Home" Height="768" Width="1024">
<Window.Resources>
<vm:vwMain x:Key="viewModel" />
</Window.Resources>
<DockPanel x:Name="viewModel"
DataContext="{Binding Source={StaticResource viewModel}}" >
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Padding="5,5,5,5" Text="Date Options: "/>
<ComboBox Margin="5" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="90"
x:Name="datOpt"
IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding Path=dateOptObj.dates}"
Background="{x:Null}" />
<DatePicker Padding="5,5,5,5"
SelectedDate="{Binding Path=dateOptObj.openDate, Mode=TwoWay}"/>
<TextBlock Padding="5,5,5,5" Text=" to "/>
<DatePicker Padding="5,5,5,5"
SelectedDate="{Binding Path=dateOptObj.closeDate, Mode=TwoWay}" />
<TextBlock Padding="5,5,5,5" Text="Rep Filter: "/>
<ComboBox Margin="5" Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="200"
x:Name="repOption"
IsSynchronizedWithCurrentItem="True"
DataContext="{Binding Source={StaticResource viewModel}}"
ItemsSource="{Binding Path=reps}"
DisplayMemberPath="AEname" />
<!--Background="{x:Null}" />-->
<Button Margin="5" Width="100" Height="20" Content="Reset Dates" Command="{Binding Path=Refill}" />
</StackPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Bottom">
<Button Margin="5" Width="100" Height="20" Content="Exit" Command="{Binding Path=ExitCommand}" />
</StackPanel>
<vm:StatPanel DockPanel.Dock="Right" Loaded="StatPanel_Loaded" />
<vm:MainBody DataContext="{Binding Source={StaticResource viewModel}}"/>
</DockPanel>
this is the code behind
public partial class MainWindow : Window
{
vwMain _viewModel;
public MainWindow()
{
InitializeComponent();
// Initialize the view Model
_viewModel = (vwMain)this.FindResource("viewModel");
}
private void StatPanel_Loaded(object sender, RoutedEventArgs e)
{
}
}
this is the part of the XAML of the UserControl
<Expander Header="New Account Stats" IsExpanded="{Binding Path=newAcctPanel, Mode=TwoWay}" ExpandDirection="Down">
<DataGrid
x:Name="m_DataGrid"
ItemsSource="{Binding}"
DataContext="{Binding Path=dashNewAcct.newAcctStats}"
VerticalAlignment="Stretch" AutoGenerateColumns="False"
ColumnWidth="Auto">
<DataGrid.Columns>
<!--<DataGridTextColumn Header="Sector"
Binding="{Binding Path=sector}" />
<DataGridTextColumn Header="Security"
Binding="{Binding Path=totalSecurities}" />
<DataGridTextColumn Header="CD"
Binding="{Binding Path=totalCD}" />
<DataGridTextColumn Header="LPC"
Binding="{Binding Path=totalLPC}" />
<DataGridTextColumn Header="BSMS"
Binding="{Binding Path=totalBSMS, StringFormat='{}{0}'}" />
<DataGridTextColumn Header="Totals"
Binding="{Binding Path=total, StringFormat='{}{0}'}" />-->
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>Sector</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Path=sector}"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Security">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="Security" Content="{Binding Path=totalSecurities}" Command="{Binding Source={StaticResource viewModel}, Path=filterGridCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PassThroughConverter}">
<Binding Path="sector"/>
<Binding ElementName="Security" Path="Name"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>CD</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="CD" Content="{Binding Path=totalCD}" Command="{Binding Source={StaticResource viewModel}, Path=filterGridCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PassThroughConverter}">
<Binding Path="sector"/>
<Binding ElementName="CD" Path="Name"/>
</MultiBinding>
</Button.CommandParameter>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>LPC</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="LPC" Content="{Binding Path=totalLPC}" Command="{Binding Source={StaticResource viewModel}, Path=filterGridCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PassThroughConverter}">
<Binding Path="sector"/>
<Binding ElementName="LPC" Path="Name" />
</MultiBinding>
</Button.CommandParameter>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>BSMS</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Name="BSMS" Content="{Binding Path=totalBSMS}" Command="{Binding Source={StaticResource viewModel}, Path=filterGridCommand}">
<Button.CommandParameter>
<MultiBinding Converter="{StaticResource PassThroughConverter}">
<Binding Path="sector"/>
<Binding ElementName="BSMS" Path="Name" />
</MultiBinding>
</Button.CommandParameter>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>Totals</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Content="{Binding Path=total}"></Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Expander>

OnCurrentChanged fires properly, your Bindings are wrong. Bind the DateTime properties to SelectedDate not Text.
<DatePicker Padding="5,5,5,5"
SelectedDate="{Binding Path=dateOptObj.openDate, Mode=TwoWay}" />
<DatePicker Padding="5,5,5,5"
SelectedDate="{Binding Path=dateOptObj.closeDate, Mode=TwoWay}" />

Related

Don't fire RelayCommand

I have a list in and relaycommand viewmodel,
private List<PurchaseInvoiceDetail> detailList = new List<PurchaseInvoiceDetail>();
public RelayCommand AddCommand { get; set; }
ICollectionView _detailCollection;
public ICollectionView DetailCollection
{
get { return _detailCollection; }
set
{
if (value != _detailCollection)
{
_detailCollection = value;
RaisePropertyChanged("DetailCollection");
}
}
}
when i use DetailCollection in constructor,dont fire relaycommand.
public PurchaseInvoiceDetailViewModel(PurchaseInvoice item)
{
if (item != null)
{
Number = item.Number;
CustomerId = item.CustomerId;
Date = new PersianDate((DateTime)item.Date);
_purchaseInvoice = item.Id;
detailList = _db.PurchaseInvoiceDetails.Where(m => m.PurchaseInvoiceId == item.Id).ToList();
CollectionViewSource.GetDefaultView(detailList).Refresh();
DetailCollection = CollectionViewSource.GetDefaultView(detailList);
}
AddCommand=new RelayCommand(() =>
{
var goods = _db.Goods.Find(GoodsId);
detailList.Add(new PurchaseInvoiceDetail(){GoodsId = GoodsId,Goods = goods,Count = Count,Price = Price,Id=0,PurchaseInvoiceId = 0});
CollectionViewSource.GetDefaultView(detailList).Refresh();
DetailCollection = CollectionViewSource.GetDefaultView(detailList);
});
}
but when i comment DetailCollection ,it work ok..
in view
<Button Margin="0 0 5 0 " Width="90" Command="{Binding AddCommand}"
Style="{StaticResource MaterialDesignRaisedButton}" >
<StackPanel Orientation="Horizontal">
<materialDesign:PackIcon Kind="Plus" />
<TextBlock >َAdd</TextBlock>
</StackPanel>
</Button>
<DataGrid CanUserDeleteRows="True" CellStyle="{StaticResource MaterialDesignDataGridCell}" Name="ListView"
IsReadOnly="True" BorderBrush="{DynamicResource MaterialDesignDivider}" VerticalAlignment="Top" BorderThickness="1" Height="200" Margin="0" AutoGenerateColumns="False"
ItemsSource="{Binding Path=DetailCollection}"
>
<DataGrid CanUserDeleteRows="True" CellStyle="{StaticResource MaterialDesignDataGridCell}" Name="ListView"
IsReadOnly="True" BorderBrush="{DynamicResource MaterialDesignDivider}" VerticalAlignment="Top"
BorderThickness="1" Height="200" Margin="0" AutoGenerateColumns="False"
ItemsSource="{Binding Path=DetailCollection}"
>
<DataGrid.Columns>
<DataGridTextColumn Width="100"
Header="کد کالا" Binding="{Binding Path=Goods.Code}"/>
<DataGridTextColumn Header="نام کالا" Binding="{Binding Path=Goods.Name}" Width="200"/>
<DataGridTextColumn Binding="{Binding Path=Count}" Width="150"
dataGridFilterLibrary:DataGridColumnExtensions.IsCaseSensitiveSearch="True"
Header="تعداد"/>
<DataGridTextColumn Header="قیمت" Binding="{Binding Path=Price}" Width="*"/>
</DataGrid.Columns>
<DataGrid.InputBindings>
<KeyBinding
Key="Delete"
Command="{Binding DeleteCommand}" CommandParameter="{Binding SelectedIndex, ElementName=ListView}"/>
</DataGrid.InputBindings>
</DataGrid>

One combo box filtering another combo box in a WPF Datagrid

I have a datagrid which has two combo box columns in it. The first combo box is a list of PersonnelTypes. Depending on which PersonnelType is selected, the second combo box should fill up with a list of Resources that match the selected PersonnelType
The problem is, lets say I have two rows of data, if I change the PersonnelType of one row, the datagrid will set the itemsource for all of the Resources in every row. I only want it to filter the row that I am in, not all the rows.
Here's the xaml for the part of the datagrid that has the combo boxes:
<DataGridTemplateColumn Header="Personnel Type" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<ComboBox Name="cmbPersonnelTypes" FontWeight="Bold" ItemsSource="{Binding ViewModel.PersonnelTypes, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem="{Binding PersonnelType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ID" DisplayMemberPath="Description" SelectionChanged="cmbPersonnelTypes_SelectionChanged" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Name" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<ComboBox Name="cmbPersonnelName" FontWeight="Bold" ItemsSource="{Binding ViewModel.ResourcesToChooseFrom, RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Resource, Mode=TwoWay}" SelectedValuePath="Refno" DisplayMemberPath="Name" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Here is the xaml for the whole data grid (just in case you need to see it):
<DataGrid AutoGenerateColumns="False" CanUserSortColumns="False" CanUserDeleteRows="True" IsReadOnly="True" Background="LightGray" CanUserAddRows="False" Margin="5" SelectedItem="{Binding SelectedLA_JobPersonnel}" ItemsSource="{Binding LA_Personnel}" Grid.ColumnSpan="4" MouseDoubleClick="DataGrid_MouseDoubleClick_1">
<DataGrid.Resources>
<ViewModels:BindingProxy x:Key="proxy" Data="{Binding}" />
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Personnel Type" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<ComboBox Name="cmbPersonnelTypes" FontWeight="Bold" ItemsSource="{Binding ViewModel.PersonnelTypes, RelativeSource={RelativeSource AncestorType=Window}}" SelectedItem="{Binding PersonnelType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ID" DisplayMemberPath="Description" SelectionChanged="cmbPersonnelTypes_SelectionChanged" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Name" Width="Auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<ComboBox Name="cmbPersonnelName" FontWeight="Bold" ItemsSource="{Binding ViewModel.ResourcesToChooseFrom, RelativeSource={RelativeSource AncestorType=Window},UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding Resource, Mode=TwoWay}" SelectedValuePath="Refno" DisplayMemberPath="Name" />
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn> <DataGridTemplateColumn Header="Date Out" Width="20*" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Background="LightGray" FontWeight="Bold" Text="{Binding DateOut, Mode=TwoWay, Converter={StaticResource thisNullDateConverter}, StringFormat={}{0:MMM-dd-yyyy hh:ss tt}}">
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<Toolkit:DateTimePicker Background="LightGray" FontWeight="Bold" Value="{Binding Path=DateOut, Mode=TwoWay, Converter={StaticResource thisNullDateConverter}}" Format="Custom" FormatString="MMM dd yyyy hh:ss tt"></Toolkit:DateTimePicker>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Date In" Width="20*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Background="LightGray" FontWeight="Bold" Text="{Binding DateIn, Mode=TwoWay, Converter={StaticResource thisNullDateConverter}, StringFormat={}{0:MMM-dd-yyyy hh:ss tt}}">
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<Toolkit:DateTimePicker Background="LightGray" FontWeight="Bold" Value="{Binding Path=DateIn, Mode=TwoWay, Converter={StaticResource thisNullDateConverter}}" Format="Custom" FormatString="MMM dd yyyy hh:ss tt"></Toolkit:DateTimePicker>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Here is the code behind for the xaml (xaml.cs):
public JobEditorViewModel ViewModel
{
get { return viewModel; }
}
private void cmbPersonnelTypes_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combobox = sender as ComboBox;
if (combobox != null)
{
var selectedPersonnelType = combobox.SelectedItem as PersonnelType;
viewModel.SetResourcesToChooseFrom(selectedPersonnelType);
}
}
Here is the code in the viewModel:
public BindingList<PersonnelType> PersonnelTypes
{
get; set;
}
public JobEditorViewModel(int jobid, string region, DataAccessDataContext db, ServiceUserControlViewModel serviceViewModel)
{
PersonnelTypes = new BindingList<PersonnelType>(_db.PersonnelTypes.OrderBy(p => p.Head).ThenBy(p => p.Description).ToList());
}
private BindingList<Resource> _resourcesToChooseFrom;
public BindingList<Resource> ResourcesToChooseFrom
{
get { return _resourcesToChooseFrom; }
set
{
_resourcesToChooseFrom = value;
NotifyPropertyChanged("ResourcesToChooseFrom");
}
}
public void SetResourcesToChooseFrom(PersonnelType personnelType)
{
ResourcesToChooseFrom =
new BindingList<Resource>(_db.Resources.Where(r => r.Head == personnelType.Head && r.Refno > 2).OrderBy(r=>r.Name).ToList());
}
If you need to see more, let me know
Well, with some help from a colleague here at work, we figured out what I needed to do. Multibinding is the answer. First off we kind of hacked around so that the two combo boxes could be in the same column by placing them both in a grid and placing the grid in the one column. So now both combo boxes can see each other because they are in the same DataGridTemplateColumn. Before, we couldn't get them to see each other because they lost scope of each other in being two separate DataGridTemplateColumns.
Here's what we did in the xaml:
<DataGridTemplateColumn Header="Personnel Type-Name" Width="Auto" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Grid.Column="0" BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding PersonnelType.Description}"/>
</Border>
<Border Grid.Column="1" BorderBrush="Black" BorderThickness="1">
<TextBlock Text="{Binding Resource.Name}"/>
</Border>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="170"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ComboBox Name="cmbPersonnelTypes" Grid.Column="0" FontWeight="Bold" ItemsSource="{Binding ViewModel.PersonnelTypes, RelativeSource={RelativeSource AncestorType=Window}, UpdateSourceTrigger=PropertyChanged}" SelectedItem="{Binding PersonnelType, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="ID" DisplayMemberPath="Description" />
<ComboBox Name="cmbPersonnelName" Grid.Column="1" FontWeight="Bold" SelectedItem="{Binding Resource, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" SelectedValuePath="Refno" DisplayMemberPath="Name" >
<ComboBox.ItemsSource>
<MultiBinding Converter="{StaticResource FilteredPersonnelConverter}">
<Binding Path="ViewModel.AvailablePersonnel" RelativeSource="{RelativeSource AncestorType=Window}"/>
<Binding Path="SelectedItem" ElementName="cmbPersonnelTypes"/>
<Binding Path="ViewModel.SelectedGlobalResourceViewOption" RelativeSource="{RelativeSource AncestorType=Window}"/>
</MultiBinding>
</ComboBox.ItemsSource>
</ComboBox>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
You'll notice there is a ValueConverter in the MultiBinding called FilteredPersonnelConverter. This value converter does all the filtering for me. Here's the code for that:
public class FilteredPersonnelListValueConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var allResources = values[0] as IList<Resource>;
var personnelType = values[1] as PersonnelType;
var selectedGlobalResourceView = values[2] as ResourceViewOption;
if (personnelType == null)
return allResources;
if(selectedGlobalResourceView.ResourceViewTitle=="Regional")
return allResources.Where(r => r.Head == personnelType.Head && r.Obsolete == false && r.Location.Region.RegionID.Trim()==SettingsManager.OpsMgrSettings.Region.Trim()).OrderBy(r => r.Name).ToList();
if (selectedGlobalResourceView.ResourceViewTitle == "Local")
return allResources.Where(r => r.Head == personnelType.Head && r.Obsolete == false && r.LocnID.Trim() == SettingsManager.OpsMgrSettings.LOCNCODE.Trim()).OrderBy(r => r.Name).ToList();
return allResources.Where(r => r.Head == personnelType.Head &&r.Obsolete==false).OrderBy(r => r.Name).ToList();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
So if anyone else is doing something like this, look into Multibinding, it will change your life
When the user changes the PersonelType dropdown in the view, the ViewModel should then filter the list of Resources (which should update the second dropdown box with the correct information).
Really your view model just needs to be set up to respond to changes on the view. That's what it boils down to.
Looking here:
public JobEditorViewModel(int jobid, string region, DataAccessDataContext db, ServiceUserControlViewModel serviceViewModel)
{
PersonnelTypes = new BindingList<PersonnelType>(_db.PersonnelTypes.OrderBy(p => p.Head).ThenBy(p => p.Description).ToList());
}
it looks like you set the personel types in the constructor, but you aren't responding to user changes. You need to do that in the PersonelType Binding in your view model.
EDIT
I see now that you're handling the selection changed. But really I think this should be done in the view model itself. Specifically because you actually access the viewmodel from the view to do make your changes.
Example
So here's my VM:
class ViewModel : INotifyPropertyChanged
{
DispatcherTimer timer = new DispatcherTimer();
public ViewModel()
{
// Create my observable collection
this.DateTimes = new ObservableCollection<DateTime>();
// Every second add anothe ritem
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}
void timer_Tick(object sender, EventArgs e)
{
// This adds to the collection
this.DateTimes.Add(DateTime.Now);
}
public ObservableCollection<DateTime> DateTimes { get; private set; }
public event PropertyChangedEventHandler PropertyChanged;
}
and My View:
<ListBox ItemsSource="{Binding DateTimes}"/>
Notice that I don't rebuild the collection. I just set it once, and then change it's size as neccesary.

Selectionchanged event firing for every row

I am using a cascading comboboxes inside datagrid.I am able to get the datas based on selectionchanged but that event is firing for every row.
Here is my code:
<sdk:datagridtemplatecolumn header="Category" width="110">
<sdk:datagridtemplatecolumn.celltemplate>
<datatemplate>
<combobox foreground="Black" height="30" isenabled="{Binding Source={StaticResource EffortViewModel}, Path=ComboBoxStatus}" itemssource="{Binding Source={StaticResource EffortViewModel},Path=ProjTypeTaskCtry}" displaymemberpath="TaskCtgyName" selectedvaluepath="TaskCtgy_FK" selectedvalue="{Binding Source={StaticResource EffortViewModel}, Path=TaskCtgy_FKField,Mode=TwoWay}" />
</datatemplate>
</sdk:datagridtemplatecolumn.celltemplate>
</sdk:datagridtemplatecolumn>
<sdk:datagridtemplatecolumn header="SubCategory" width="110">
<sdk:datagridtemplatecolumn.celltemplate>
<datatemplate>
<combobox foreground="Black" height="30" isenabled="{Binding Source={StaticResource EffortViewModel}, Path=ComboBoxStatus}" itemssource="{Binding Source={StaticResource EffortViewModel},Path=SubCtry,Mode=OneWay}" displaymemberpath="TaskSubCtgyName" selectedvaluepath="{Binding TaskSubCtgy_PK, Mode=TwoWay}" selectedvalue="{Binding TaskSubCtgy_FKField,Mode=OneTime}" selectedindex="{Binding TaskSubCtgy_FKField}" />
</datatemplate>
</sdk:datagridtemplatecolumn.celltemplate>
</sdk:datagridtemplatecolumn>
I had the same problem in Silverlight MVVM. I found a solution for this from somewhere. Hope this will help you.
namespace Test
{
public class ComboBoxSelectionChange : TriggerAction<DependencyObject>
{
public ComboBoxSelectionChange()
{
}
public ComboBox DayComboBox
{
get { return (ComboBox)GetValue(DayComboBoxProperty); }
set { SetValue(DayComboBoxProperty, value); }
}
public static readonly DependencyProperty DayComboBoxProperty =
DependencyProperty.Register("DayComboBox",
typeof(ComboBox),
typeof(ComboBoxSelectionChange),
new PropertyMetadata(null, OnDayComboBoxPropertyChanged));
private static void OnDayComboBoxPropertyChanged(DependencyObjectd, DependencyPropertyChangedEventArgs e)
{
var source = d as ComboBoxSelectionChange;
if (source != null)
{
var value = (ComboBox)e.NewValue;
}
}
protected override void Invoke(object o)
{
if (this.DayComboBox != null)
{
//this method will execute when the selection is changed
}
}
}
}
Use the Test namespace in Usercontrol assembly
xmlns:Common="clr-namespace:Test"
<UserControl.Resources>
<Common:ComboBoxSelectionChange x:Name="ComboBoxItem"/>
</UserControl.Resources>
<DataTemplate x:Key="EditMondayDataTemplate">
<ComboBox x:Name="cmbMonday" Height="26" Margin="3" ItemsSource="{Binding Monday,Mode=OneTime}" DisplayMemberPath="displayText" SelectedItem="{Binding Path=MonSelected,Mode=TwoWay}" HorizontalAlignment="Center" VerticalAlignment="Center" Width="80">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<Common:ComboBoxSelectionChange DayComboBox="{Binding ElementName=cmbMonday}" TextParam="Monday"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ComboBox>
</DataTemplate>

Binding not triggering Action<>

I have some code like this
this is a custom datagrid which displays hierarchical data which should close and open.
<UserControl.DataContext>
<loc:Def1 x:Name="initdef1"/>
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" HorizontalAlignment="Center" VerticalAlignment="Center" >
<data:DataGrid x:Name="_dataGrid" AutoGenerateColumns="False"
ItemsSource="{Binding Display, Mode=OneWay}"
SelectionMode="Extended" >
<data:DataGrid.Columns>
<data:DataGridTemplateColumn Header="Col1">
<data:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" >
<CheckBox IsChecked="{Binding IsExpanded, Mode=TwoWay}" Margin="{Binding Path=Level, Converter={StaticResource ConvertToThickness}}"/>
<TextBlock Text="{Binding Cells[0]}" Margin="4" />
</StackPanel>
</DataTemplate>
</data:DataGridTemplateColumn.CellTemplate>
</data:DataGridTemplateColumn>
<data:DataGridTextColumn Header="Col2" Binding="{Binding Cells[1]}" />
</data:DataGrid.Columns>
</data:DataGrid>
with this is def1
this class has the actual logic for all the processing and loading and mapping the data to the grid.
public Def1()
{
_columns = new List<ColumnDef>();
_source = new ObservableCollection<Def2>();
Def2.RowExpanding += new Action<Def2>(RowDef_RowExpanding);
Def2.RowCollapsing += new Action<Def2>(RowDef_RowCollapsing);
}
void RowDef_RowExpanding(Def2 row)
{
foreach (RowDef child in row.Children)
child.IsVisible = true;
OnPropertyChanged("Display");
}
void RowDef_RowCollapsing(Def2 row)
{
foreach (Def2 child in row.Children)
{
if (row.IsExpanded.HasValue && row.IsExpanded.Value)
RowDef_RowCollapsing(child);
child.IsVisible = false;
}
OnPropertyChanged("Display");
}
and this in def2
this class has the logic on how should the rows behave.
public bool? IsExpanded
{
get { return _isExpanded; }
set
{
if (_isExpanded != value)
{
_isExpanded = value;
if (_isExpanded.Value)
{
if (RowDef.RowExpanding != null)
RowDef.RowExpanding(this);
}
else
{
if (RowDef.RowCollapsing != null)
RowDef.RowCollapsing(this);
}
}
}
}
The thing is when the checkbox is checked or unchecked nothing happens.
Ok I found the answer from a similar post wpf 4.0 datagrid template column two-way binding problem
So I changed the code to
<CheckBox IsChecked="{Binding Mode=TwoWay, Path=IsExpanded, UpdateSourceTrigger=PropertyChanged}" Margin="{Binding Path=Level, Converter={StaticResource ConvertToThickness}}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" x:Name="checkbox1"/>
Now it works.
But can anybody explain why i needed to set UpdateSourceTrigger=PropertyChanged ?
It's not always required.
Thanks

How to get cell lreference

If I have a control (combobox, with a SelectionChanged-event in code-behind) in DataGrid.
So, from _SelectionChanged-event, can I get reference of it's container-cell of the grid?
Plz Help!!
<DataGridTemplateColumn Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=QuotationItemCode}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<ComboBox Height="22" Width="100" Name="cmbQuotationItemCode"
ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.vwProducts}"
DisplayMemberPath="itM_Code"
SelectedValuePath ="itM_Id"
Tag="{Binding RelativeSource={RelativeSource Self}, Path=SelectedItem.Row[2]}"
SelectedValue="{Binding Path=QuotationItemId}"
Text="{Binding Path=QuotationItemCode}" SelectionChanged="cmbQuotationItemCode_SelectionChanged">
</ComboBox>
<TextBlock Name="txtQuotationItemDescription" Text="{Binding Path=DetailDescription, IsAsync=True}" Height="19"></TextBlock>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
You can walk the visual tree up from the ComboBox until you hit a DataGridCell, using VisualTreeHelper like this:
private static T FindAncestor<T>(DependencyObject child) where T : DependencyObject
{
var parentObject = VisualTreeHelper.GetParent(child);
if(parentObject == null || parentObject is T) {
return (T)parentObject;
}
return FindAncestor<T>(parentObject);
}
private void cmbQuotationItemCode_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var cell = FindAncestor<DataGridCell>((DependencyObject)sender);
...
}
That said, don't forget about DataGridTemplateColumn.CellStyle - perhaps you can solve your problem with a Style!

Resources