CellTemplateSelector won't choose template automatically - wpf

I have two templates for DataGridTemplateColumn
<DataTemplate x:Key="firstTemplate">
<UniformGrid Grid.Column="1" Columns="2">
<Label Background="{Binding Path=Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=Value}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="Visible" />
</UniformGrid>
</DataTemplate>
<DataTemplate x:Key="secondTemplate">
<UniformGrid Grid.Column="1" Columns="{Binding Converter={StaticResource getColumnsAmount}}">
<Label Background="{Binding Path=ColorData_1.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_1,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_1.IsSelected,
Converter={StaticResource boolConvert}}" />
<Label Background="{Binding Path=ColorData_2.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_2,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_2.IsSelected,
Converter={StaticResource boolConvert}}" />
<Label Background="{Binding Path=ColorData_3.Color,
Converter={StaticResource gradientBrush}}"
Content="{Binding Path=ColorData_3,
Converter={StaticResource ValueRangeConvert}}"
Style="{StaticResource WhiteCellLabelStyle}"
Visibility="{Binding Path=ColorData_3.IsSelected,
Converter={StaticResource boolConvert}}" />
</UniformGrid>
</DataTemplate>
<DataGrid Name="dgLegend"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AutoGenerateColumns="False"
Background="{x:Null}"
HeadersVisibility="None"
IsHitTestVisible="True"
IsReadOnly="True"
ItemsSource="{Binding}">
<DataGrid.Columns>
<DataGridTemplateColumn Width="Auto"
Header="exp"
IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Border Background="{Binding Path=Color>
<Label Content="{Binding Path=Color}" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="*" Header="Range">
<DataGridTemplateColumn.CellTemplateSelector>
<local:LegendDisplayModeTemplateSelector
firstTemplate="{StaticResource firstTemplate}"
secondTemplate="{StaticResource secondTemplate}" />
</DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
My TemplateSelector
public class LegendDisplayModeTemplateSelector : DataTemplateSelector
{
public DataTemplate firstTemplate
{
get;
set;
}
public DataTemplate secondTemplate
{
get;
set;
}
public DisplayMode displayMode
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
TSOptions opts = (TSOptions)item;
//some other code
}
}
The problem is the item in SelectTemplate(object item, DependencyObject container) always get null

I found the answer.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/b47ac38a-077f-41da-99b1-8b88add693d8?prof=required
He used this way:
class UserCellEdit : DataTemplateSelector
{
public override DataTemplate
SelectTemplate(object item, DependencyObject container)
{
ContentPresenter presenter = container as ContentPresenter;
DataGridCell cell = presenter.Parent as DataGridCell;
Guideline_node node = (cell.DataContext as Guideline_node);
//,...... etc. the rest of the code
}
}

I used this solution:
public class EmployeeListDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is Employee)
{
Employee employee = item as Employee;
if (employee.Place == "UK")
return element.FindResource("UKdatatemp") as DataTemplate;
else
return element.FindResource("Otherdatatemp") as DataTemplate;
}
return null;
}
}

Related

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>

How can I track the selected TabPage's DataContext from my ViewModel?

I have TabItem class:
public class TabItem
{
public string Header { get; set; }
public IView Content { get; set; }
}
and in my model:
public ObservableCollection<TabItem> Tabs
{
get { return _tabs; }
set
{
if(_tabs!=value)
{
_tabs = value;
RaisePropertyChanged("Tabs");
}
}
}
public TabItem CurrentTabItem
{
get { return _currentTabItem; }
set
{
if (_currentTabItem != value)
{
}
_currentTabItem = value;
RaisePropertyChanged("CurrentTabItem");
}
}
In View i'm binding to ModelView:
<TabControl x:Name="shellTabControl" ItemsSource="{Binding Tabs}"
IsSynchronizedWithCurrentItem="True" SelectionChanged="ShellTabControlSelectionChanged">
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Content}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
From view i want to change ViewModel's CurrentTabItem property:
private void ShellTabControlSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if(e.Source is TabItem)
{
var tabItem = e.Source as TabItem;
ViewModel.CurrentTabItem = tabItem; //don't work
}
}
What is the best approach to convert TabControl's TabItem to my TabItem?
Maybe it is better to use SelectedItem="{Binding CurrentTabItem, Mode=TwoWay, UpdateSourceTrigget=PropertyChanged}"?
<TabControl x:Name="shellTabControl" ItemsSource="{Binding Tabs}"
IsSynchronizedWithCurrentItem="True"
SelectionChanged="ShellTabControlSelectionChanged"
SelectedItem={Binding Path=CurrentTabItem,Mode=Twoway}>
<TabControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Header}"/>
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate>
<ContentPresenter Content="{Binding Content}"/>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
This will get you the selected TabItem.......
Also change the Name of your Custom "TabItem" its confusing ;)

change the template of an item after clicking on it

i have a class named :
public class CountryTemplateSelector : ContentControl
{
public DataTemplate TrueTemplate
{
get;
set;
}
public DataTemplate FalseTemplate
{
get;
set;
}
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
Shopping_Ingredients itemAux = item as Shopping_Ingredients;
if (itemAux != null)
{
if (itemAux.IsMarked == true)
return TrueTemplate;
else
return FalseTemplate;
}
return base.SelectTemplate(item, container);
}
public virtual DataTemplate SelectTemplate(object item, DependencyObject container)
{
return null;
}
protected override void OnContentChanged(object oldContent, object newContent)
{
base.OnContentChanged(oldContent, newContent);
ContentTemplate = SelectTemplate(newContent, this);
}
}
and a DataTemplate declared in App.xaml :
<DataTemplate x:Key="SelectorForCheckbox">
<local:CountryTemplateSelector Content="{Binding}">
<local:CountryTemplateSelector.TrueTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="82">
<CheckBox Name="cb1" FontSize="15" IsChecked="{Binding Path=IsMarked, Mode=TwoWay}" Margin="0,4" RenderTransformOrigin="0.485,0.365" VerticalContentAlignment="Bottom" />
<TextBlock Text="{Binding AmountToString}" Margin="15,0,5,0" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="24"/>
</StackPanel>
</DataTemplate>
</local:CountryTemplateSelector.TrueTemplate>
<local:CountryTemplateSelector.FalseTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="82">
<CheckBox Name="cb1" FontSize="15" IsChecked="{Binding Path=IsMarked, Mode=TwoWay}" Margin="0,4" RenderTransformOrigin="0.485,0.365" VerticalContentAlignment="Bottom" />
<TextBlock Text="TEST" Margin="15,0,5,0" VerticalAlignment="Center" HorizontalAlignment="Left" FontSize="24"/>
</StackPanel>
</DataTemplate>
</local:CountryTemplateSelector.FalseTemplate>
</local:CountryTemplateSelector>
</DataTemplate>
and a LongListSelector :
<toolkit:LongListSelector x:Name="recipe1" Background="Transparent"
ItemTemplate="{StaticResource SelectorForCheckbox}"
ListHeaderTemplate="{StaticResource citiesListHeader}"
ListFooterTemplate="{StaticResource citiesListFooter}"
GroupHeaderTemplate="{StaticResource groupHeaderTemplate}"
GroupItemTemplate="{StaticResource groupItemTemplate}" >
<toolkit:LongListSelector.GroupItemsPanel>
<ItemsPanelTemplate>
<toolkit:WrapPanel/>
</ItemsPanelTemplate>
</toolkit:LongListSelector.GroupItemsPanel>
</toolkit:LongListSelector>
The LongListSelector launches ok, and the templates are shown ok. The problem is that i would like to be able to change the template of the specific item clicked. How can i do so?
We should be able to set the templates in code. See this StackOverflow question. Make sure that all the templates needed are resources in the App.xaml or in your specific UserControl. My example is from a button click, but the same approach should apply elsewhere in code. I'm not 100% certain it should be cast to ControlTemplate. It will probably very per template.
public void CLick_Method(object sender, RoutedEventArgs e)
{
this.recipe1.ItemTemplate = (ControlTemplate)Resources["SelectorForX"];
this.recipe1.ListHeaderTemplate= (ControlTemplate)Resources["NewListHeaderTemplate"];
// etc.
}

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

Resources