ToggleButton change background when pressed (but only once) - c#

When a button gets pressed the background (Rectangle Fill) of the button changes. So the user can see what buttons have been pressed and what not.
Problem:
I use a trigger and a Togglebutton to perform the "IsChecked" to change the background.
But the background change may only happens 1 time.
For example:
Button Background = black --> PRESS --> Button Background = blue
But when i press the button again the Button BackGround changes back to black (since its a ToggleButton).
How can i make sure the background only changes 1 time?
EDIT: The button must remain enabled, because a user gives in a reason when they press the button. Meaning if they pick the wrong reason they are able to change it.
<Style x:Key="ButtonStyleReg" TargetType="{x:Type myClasses:RegButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ToggleButton}">
<Grid x:Name="registrationButton">
<Rectangle Name="rectangleBtn" Fill="#FF89959A" Height="Auto" RadiusY="15" RadiusX="15" Stroke="White" Width="Auto"/>
<TextBlock x:Name="reason" TextWrapping="Wrap"
Text="{Binding Reason, StringFormat=\{0\}}"
HorizontalAlignment="Center" Margin="0,7.5,0,0" Height="Auto"
VerticalAlignment="Top" FontWeight="Bold" >
</TextBlock>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<!--<Trigger Property="IsDefaulted" Value="True"/>-->
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="rectangleBtn" Property="Fill" Value="blue" />
</Trigger>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="FontSize" Value="10.667"/>
Listbox that implements the style:
<ListBox x:Name="lbRegistration" ItemsSource="{Binding RegBtns, ElementName=Window}" Background="{x:Null}"
BorderBrush="{x:Null}" Grid.Column="1"
ScrollViewer.HorizontalScrollBarVisibility="Hidden" ScrollViewer.VerticalScrollBarVisibility="Disabled" Height="75">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegistration}"
Click="RegistrationButton_Click"
Title="{Binding Title}"
Oorzaak="{Binding Oorzaak}"
DuurStilstand="{Binding DuurStilstand,
Converter={StaticResource DateTimeConverter}}"
BeginStilstand="{Binding BeginStilstand}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Best Regards,
Pete

Very simple would be if you can access the rectangle from code behind:
rectangleBtn.Fill = Brushes.Blue;
If you can't access it - make yourself two styles.
The one that is the original style, the other one is the Blue Style which shall be applied when the user clicks.
In the code behind, on event Click="RegistrationButton_Click"
Set the Style to the BlueStyle.
RegistrationButton.Style = this.FindResource("ButtonStyleRegistration") as Style;
Since you always want it blue, this code is enough as it is. It will always make it Blue for you.
The first time, and any other time.
That way you achieve your requirement and the style will change only once.
When the window is loaded, it will load into the original style (the first style).
So put in your XAML the style "Black" and in the code behind as shown above.
Then this must be removed:
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="rectangleBtn" Property="Fill" Value="blue" />
</Trigger>
Then this:
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegistration}"
Click="RegistrationButton_Click"
Shall be:
<myClasses:RegistrationButton x:Name="RegistrationButton" HorizontalAlignment="Center" Height="71" Width="148"
Margin="10,0,5,0"
Style="{DynamicResource ButtonStyleRegBlack}"
Click="RegistrationButton_Click"
That is all.

If you're using an MVVM approach I would recommend binding the background and the Click command to members in the ViewModel. The first time the button is clicked it sets a flag and changes the background color. The next time the button is clicked, if the flag is set, the command returns without changing the background.
XAML:
<ToggleButton Background="{Binding MyBackground}" Command="{Binding OnClickCmd}"/>
ViewModel
public class ViewModel : INotifyPropertyChanged
{
public Brush MyBackground
{
get { return background_; }
set {
background_ = value;
PropertyChanged(this, new PropertyChangedEventArg("MyBackground");
}
}
public ICommand OnClickCmd
{
get {
return new DelegateCommand(()=>{ // DelegateCommand implements ICommand
if(!isBackgroundSet) {
background = Brushes.Red;
isBackgroundSet_ = true;
}
});
}
}
private Brush background_;
private bool isBackgroundSet_;
private event PropertyChangedEventHandler PropertyChagned;
}

Related

Launch MouseEnter event Image from XAML dictionnary with MVVM

I have a template for a DataGrid located in a ResourceDictionary.
BlockStyles.xaml
<Style TargetType="DataGrid" x:Key="SearchExpGrid">
<Setter Property="AlternatingRowBackground" Value="#4C87C6ff"/>
<Setter Property="GridLinesVisibility" Value="None"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="HeadersVisibility" Value="Column"/>
<Setter Property="CellStyle">
<Setter.Value ... />
</Setter>
<Setter Property="RowStyle">
<Setter.Value ... />
</Setter>
<Setter Property="ColumnHeaderStyle">
<Setter.Value>
<Style TargetType="DataGridColumnHeader">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border
x:Name="Border" Background="White" BorderBrush="#4C87C6" BorderThickness="1" >
<StackPanel Orientation="Horizontal" Margin="5,5" HorizontalAlignment="Center">
<TextBlock
x:Name="TxtB" Text="{Binding}"
Foreground="#4C87C6" FontWeight="DemiBold" HorizontalAlignment="Center"/>
<Image Source="../Images/dropdown.png"
Width="10" Height="10" Margin="5,0,5,0"
MouseEnter="DropdownButton_MouseEnter"
MouseLeave="DropdownButton_MouseLeave"
MouseEnter="DropdownButton_Click"/>
</StackPanel>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Border" Property="Background" Value="#4C87C6"/>
<Setter TargetName="TxtB" Property="Foreground" Value="White"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Setter.Value>
</Setter>
</Style>
I always have an error because the function can't find it's definition.
I first implemented the function in the View file where the style is used but it doesn't work.
I tried this method from StackOverflow using a resource class inheriting ResourceDictionnary but got the same error.
I then tried to use ICommand and RelayCommand to execute the function from the ViewModel but didn't got any result.
I also didn't find where I could add an EventHandler ImgDropdownButton.MouseEnter += new MouseEventHandler(MouseEnter_DropdownButton); using MVVM.
Is there a better solution for this kind of behaviour or if adding an EventHandler is the best solution, where sould be the best place to add it ?
Thanks in advance
Edit :
I managed to handle the function using a code-behind file for my ResourceDictionary following this.
BlockStyles.xaml.cs
private void DropdownButton_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
{
Mouse.OverrideCursor = Cursors.Hand;
}
private void DropdownButton_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
{
Mouse.OverrideCursor = Cursors.Arrow;
}
private void DropdownButton_Click(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
//Function to show the popup
}
The MouseEnter and MouseLeave function are working, but I don't understand how to use the function to make my popup appear.
What I'm trying to do is that when I click on the Dropdown Image on the column header, I want to display a Popup, like an Excel one. This will allow the user to filter the columns values.
The file where my Grid and Popup are : (SearchExpView.xaml)
<Grid Grid.Row="2" Grid.Column="1">
<searchcomponents:ExpListView x:Name="ExpDatagrid"
DataContext="{Binding OExpListVM}"
Width="auto" Height="auto"/>
</Grid>
<Popup x:Name="PopupFiltre">
PopupFiltre content
</Popup>
Definition of my Datagrid : (ExpListView.xaml)
<Grid>
<DataGrid x:Name="ExpGrid" Style="{StaticResource SearchExpGrid}"
BorderThickness="0" BorderBrush="#4C87C6"
HorizontalAlignment="Left" VerticalAlignment="Top"
MinHeight="200" Height="auto" Margin="10,10,0,0"
MinWidth="780" Width="auto"
ItemsSource="{Binding}" DataContext="{Binding tableExpertise.DefaultView}"
AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True">
<DataGrid.InputBindings>
<MouseBinding MouseAction="LeftDoubleClick"
Command="{Binding DataContext.OnRowDoubleClickedCommand, RelativeSource={RelativeSource AncestorType=UserControl}}"
CommandParameter="{Binding ElementName=ExpGrid, Path=CurrentItem}"/>
</DataGrid.InputBindings>
<DataGrid.ContextMenu>
<ContextMenu Name="dgctxmenu">
<Separator></Separator>
</ContextMenu>
</DataGrid.ContextMenu>
</DataGrid>
</Grid>
I'm looking for a way to be able to implement this popup fonction but I can't find out how to link everything together.
My Window is SearchExpView.xaml (with the Datagrid and the Popup). My Datagrid component is defined in ExpListView.xaml and styled in BlockStyles.xaml, which is not a window. I want to make the Popup (in SearchExpView.xaml) visible by clicking on the dropdown button (defined in BlockStyles.xaml)
Then you need to get a reference to the Popup in the window from the ResourceDictionary somehow.
You could for example use the static Application.Current.Windows property:
var window = Application.Current.Windows.OfType<SearchExpView>().FirstOrDefault();
if (window != null)
window.PopupFiltre.IsOpen = true;
Also make sure that you make the Popup accessible from outside the SearchExpView class:
<Popup x:Name="PopupFiltre" x:FieldModifier="internal">
...

How to persistently change color of ListBox SelectedItem after selecting

I have a listbox that loads it's items with Foreground color set to red. What I'd like to do is: upon selecting an item with the mouse, change the foreground color of SelectedItem to black, but make the change persistent so that after deselecting the item, color remains black. Incidentally I want to implement this as a way of showing 'read items' to the user.
Essentially I want something like an implementation of the common property trigger like the code below, but not have the style revert after deselection. I've played around with event triggers as well without much luck.
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True" >
<Setter Property="Foreground" Value="Black" /> //make this persist after deselection
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
Thanks in advance!
You could animate the Foreground property:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Foreground" Value="Red" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<ColorAnimation Storyboard.TargetProperty="(ListBoxItem.Foreground).(SolidColorBrush.Color)"
To="Black" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
The downside of this simple approach is that the information is not stored somewhere. This is pure visualization without any data backing. In order to persist the information, so that restarting the application shows the same previous state, you should introduce a dedicated property to your data model e.g IsMarkedAsRead.
Depending on your requirements, you can override the ListBoxItem.Template and bind ToggleButton.IsChecked to IsMarkedAsRead or use a Button which uses a ICommand to set the IsMarkedAsRead property. There are many solutions e.g. implementing an Attached Behavior.
The following examples overrides the ListBoxItem.Template to turn the ListBoxItem into a Button. Now when the item is clicked the IsMarkedAsRead property of the data model is set to true:
Data model
(See Microsoft Docs: Patterns - WPF Apps With The Model-View-ViewModel Design Pattern for an implementation example of the RelayCommand.)
public class Notification : INotifyPropertyChanged
{
public string Text { get; set; }
public ICommand MarkAsReadCommand => new RelayCommand(() => this.IsMarkedAsRead = true);
public ICommand MarkAsUnreadCommand => new RelayCommand(() => this.IsMarkedAsRead = false);
private bool isMarkedAsRead;
public bool IsMarkedAsRead
{
get => this.isMarkedAsRead;
set
{
this.isMarkedAsRead = value;
OnPropertyChanged();
}
}
#region INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
ListBox
<ListBox ItemsSource="{Binding Notifications}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Background="{TemplateBinding Background}">
<Button x:Name="ContentPresenter"
ContentTemplate="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}, Path=ItemTemplate}"
Content="{TemplateBinding Content}"
Command="{Binding MarkAsReadCommand}"
Foreground="Red">
<Button.Template>
<ControlTemplate TargetType="Button">
<Border>
<ContentPresenter />
</Border>
</ControlTemplate>
</Button.Template>
</Button>
</Border>
<ControlTemplate.Triggers>
<DataTrigger Binding="{Binding IsMarkedAsRead}" Value="True">
<Setter TargetName="ContentPresenter" Property="Foreground" Value="Green" />
</DataTrigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type Notification}">
<TextBlock Text="{Binding Text}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks a lot #BionicCode for the comprehensive answer. I ended up going with another solution which may or may not be good convention; I am a hobbyist.
Firstly, I don't need databacking / persistence.
Concerning the data model solution and overriding ListBoxItem.Template, I am using a prededfined class 'SyndicationItem' as the data class (my app is Rss Reader). To implement your datamodel solution I guess I could hack an unused SyndicationItem property, or use SyndicationItem inheritance for a custom class (I'm guessing this is the most professional way?)
My complete data model is as follows:
ObservableCollection >>> CollectionViewSource >>> ListBox.
Anyway I ended up using some simple code behind which wasn't so simple at the time:
First the XAML:
<Window.Resources>
<CollectionViewSource x:Key="fooCollectionViewSource" Source="{Binding fooObservableCollection}" >
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="PublishDate" Direction="Descending" />
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<Style x:Key="DeselectedTemplate" TargetType="{x:Type ListBoxItem}">
<Setter Property="Foreground" Value="Gray" />
</Style>
</Window.Resources>
<ListBox x:Name="LB1" ItemsSource="{Binding Source={StaticResource fooCollectionViewSource}}" HorizontalContentAlignment="Stretch" Margin="0,0,0,121" ScrollViewer.HorizontalScrollBarVisibility="Disabled" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="80" />
</Grid.ColumnDefinitions>
<TextBlock MouseDown="TextBlock_MouseDown" Grid.Column="0" Text="{Binding Path=Title.Text}" TextWrapping="Wrap" FontWeight="Bold" />
<TextBlock Grid.Column="1" HorizontalAlignment="Right" TextAlignment="Center" FontSize="11" FontWeight="SemiBold"
Text="{Binding Path=PublishDate.LocalDateTime, StringFormat='{}{0:d MMM, HH:mm}'}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now the code behind:
Solution 1: this applies a new style when listboxitem is deselected. Not used anymore so the LB1_SelectionChanged event is not present in the XAML.
private void LB1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (e.RemovedItems.Count != 0)
{
foreach (var lbItem in e.RemovedItems)
{
//get reference to source listbox item. This was a pain.
int intDeselectedItem = LB1.Items.IndexOf(lbItem);
ListBoxItem lbi = (ListBoxItem)LB1.ItemContainerGenerator.ContainerFromIndex(intDeselectedItem);
/*apply style. Initially, instead of applying a style, I used mylistboxitem.Foreground = Brushes.Gray to set the text color.
Howver I noticed that if I scrolled the ListBox to the bottom, the text color would revert to the XAML default style in my XAML.
I assume this is because of refreshes / redraws (whichever the correct term). Applying a new style resolved.*/
Style style = this.FindResource("DeselectedTemplate") as Style;
lbi.Style = style;
}
}
}
Solution 2: The one I went with. Occurs on SelectedItem = true, same effect as your first suggestion.
private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
TextBlock tb = e.Source as TextBlock;
tb.Foreground = Brushes.Gray;
}

Ellipse as radio button

In my project, I have a little color picker that is in fact an ItemsControl with SolidColorBrushes as items, and an Ellipse as ItemTemplate.
I want the user to pick a color, when he clicks the Ellipse I want the BorderThickness to go from 0 to 2, in order to highlight the selected Ellipse.
I already managed to change the BorderThickness when the user hovers the item, using triggers. But where would I save the information about which color is selected? I can not really think of an approach here. And how can I manage that the trigger on hovering still fires even when the trigger for selected has already been activated?
Thanks in advance.
Here's some markup and code to consider.
The Selected item of the listbox is also made the current item of the collectionview. You can bind that, get it in code in the viewmodel and also navigate to next and previous.
https://msdn.microsoft.com/en-us/library/system.windows.data.collectionview.currentitem%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
I bind the rectangle to the current brush so when you select a different entry that changes. The listbox already has a lightblue background appears as you mouseover an item which highlights it somewhat. My trigger also increases the size of the ellipse a bit.
<Window.DataContext>
<local:MainWIndowViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox ItemsSource="{Binding BrushesView}"
IsSynchronizedWithCurrentItem="True"
>
<ListBox.ItemTemplate>
<DataTemplate>
<Ellipse Fill="{Binding}" Height="20" Width="20">
<Ellipse.Style>
<Style TargetType="Ellipse">
<Setter Property="Stroke" Value="Gray"/>
<Setter Property="StrokeThickness" Value="1"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={
RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}}"
Value="True">
<Setter Property="Ellipse.Stroke" Value="Black"/>
<Setter Property="Ellipse.StrokeThickness" Value="2"/>
</DataTrigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="RenderTransform">
<Setter.Value>
<ScaleTransform ScaleX="1.2" ScaleY="1.2" />
</Setter.Value>
</Setter>
</Trigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Rectangle
Grid.Column="1"
Width="40"
Height="40"
Fill="{Binding BrushesView/}"/>
</Grid>
The viewmodel:
public class MainWIndowViewModel
{
public CollectionView BrushesView { get; set; }
private ObservableCollection<SolidColorBrush> BrushesList { get; set; } =
new ObservableCollection<SolidColorBrush>
{
Brushes.Yellow, Brushes.Pink, Brushes.Blue, Brushes.Green, Brushes.Red, Brushes.Purple
};
public MainWIndowViewModel()
{
BrushesView = (CollectionView)new CollectionViewSource { Source = BrushesList }.View;
}
}

WPF Change Window Layout Based on Combo Box Selection Using MVVM

I need to change the layout of my window based on what the user selects in a combo box. I've made a stab at what one way might be but feel like it is clunky and hacked together. Im certain their must be a cleaner MVVM solution.
My thoughts where to have multiple dock panels in my GroupBox Whose visibility is set to collapse. When the selection is made, the appropriate dockpanel will be set to visible. I attempted to find a way to do this inside the view model with no success. I also couldn't help but think my attempts are violating MVVM.
XAML
<GroupBox Header="Options">
<Grid>
<DockPanel LastChildFill="False" x:Name="syncWellHeadersDockPanel" Visibility="Collapsed">
<Button DockPanel.Dock="Right" Content="Test"></Button>
</DockPanel>
<DockPanel LastChildFill="False" x:Name="SyncDirectionalSurveyDockPanel" Visibility="Collapsed">
<Button DockPanel.Dock="Left" Content="Test02"></Button>
</DockPanel>
</Grid>
</GroupBox>
ViewModel - Property for Selected Item for ComboBox
private StoredActionsModel _selectedStoredAction = DefaultStoredAction.ToList<StoredActionsModel>()[0];
public StoredActionsModel SelectedStoredAction
{
get { return _selectedStoredAction; }
set
{
if (value != _selectedStoredAction)
{
// Unset Selected on old value, if there was one
if (_selectedStoredAction != null)
{
_selectedStoredAction.Selected = false;
}
_selectedStoredAction = value;
// Set Selected on new value, if there is one
if (_selectedStoredAction != null)
{
_selectedStoredAction.Selected = true;
}
OnPropertyChanged("SelectedStoredAction");
if (_selectedStoredAction.StoredActionID == 4)
{
//X:SyncWellHeaderDockPanel.visibility = true?????
}
}
}
}
Here's a pure-XAML way to do exactly what you're asking how to do. It's a bit verbose.
Notice that we no longer set Visibility in attributes on the DockPanels. If we still did that, the values set in the Style trigger would be overridden by the attributes. That's the way dependency properties work.
<GroupBox Header="Options">
<Grid>
<DockPanel LastChildFill="False" x:Name="syncWellHeadersDockPanel" >
<Button DockPanel.Dock="Right" Content="Test"></Button>
<DockPanel.Style>
<Style TargetType="DockPanel" >
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger
Binding="{Binding SelectedStoredAction.StoredActionID}"
Value="1"
>
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</DockPanel.Style>
</DockPanel>
<DockPanel LastChildFill="False" x:Name="SyncDirectionalSurveyDockPanel">
<Button DockPanel.Dock="Left" Content="Test02"></Button>
<DockPanel.Style>
<Style TargetType="DockPanel" >
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger
Binding="{Binding SelectedStoredAction.StoredActionID}"
Value="2"
>
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</DockPanel.Style>
</DockPanel>
</Grid>
</GroupBox>
Another way to do this would be to pass SelectedStoredAction.StoredActionID to a DataTemplateSelector, but that involves writing C# code that knows what your XAML resource keys are, and I'm not a fan.

Interactive Grid WPF

I am currently working in C# WPF 4.5 and am attempting to create an interactive grid. Given the grid cell square size (width = height), number of columns and number of rows, I'd like to dynamically generate the grid on the screen.
For the generated grid, I'd like the grid lines to be visible. I'm thinking this could be emulated by just drawing a border within each cell if nothing else. On top of all this, I need an event to be able to determine what cell the user clicks on (i.e., on click return gird column and row) with the ability to select one or more cell at a time.
Any help or ideas on how I could create something like this or is there a better way to go about it? Thanks in advance!
Edit:
So here's some progress I've made:
Created a custom checkbox:
<Style x:Key="styleCustomCheckBox" TargetType="{x:Type CheckBox}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type CheckBox}">
<Grid x:Name="Background" Background="Transparent">
<Rectangle x:Name="fillCheckBox"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsChecked" Value="False">
<Setter TargetName="fillCheckBox" Property="Fill" Value="Transparent"/>
</Trigger>
<Trigger Property="IsChecked" Value="True">
<Setter TargetName="fillCheckBox" Property="Fill" Value="Red"/>
<Setter TargetName="fillCheckBox" Property="Opacity" Value=".3"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
And then just populate a grid with the custom checkboxes of that style:
<CheckBox Grid.Column="1" Grid.Row="1" Style="{StaticResource styleCustomCheckBox}" />
So now I'd like to map each of checkboxes within the grid where I can gather whether the checkbox is checked or not and what grid row and column it is in, how would I go about this?
I would use an ItemsControl with its ItemsPanelTemplate set to a UniformGrid, and it's ItemTemplate set to your CheckBox
It would be easiest if you could bind your ItemsControl.ItemsSource to a collection of data objects in your code behind. For example:
<ItemsControl ItemsSource="{Binding MyCollection}">
<!-- ItemsPanelTemplate -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="5" Columns="5" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<!-- ItemTemplate -->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Red" BorderThickness="1">
<CheckBox Style="{StaticResource styleCustomCheckBox}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
If you needed to specify the Row or Column index of the checked item, you could add that to your data item and use a regular Grid instead of a UniformGrid, and apply an ItemContainerStyle like this:
<!-- ItemContainerStyle -->
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
<Setter Property="Grid.Row" Value="{Binding RowIndex}" />
</Style>
</ItemsControl.ItemContainerStyle>
To determine the item clicked on, that depends on how you structure your data object and what you actually want to do in your click.
If you wanted the data item behind the square, you could just use the DataContext, such as
void MyCheckBox_Clicked(object sender, EventArgs e)
{
var selectedItem = ((CheckBox)sender).DataContext;
}
Or if you had something like a data item with an IsChecked property like this:
<CheckBox IsChecked="{Binding IsChecked}"
Style="{StaticResource styleCustomCheckBox}" />
You could easily attach an event to the PropertyChanged event for the data item's IsChecked property, and run some code there.
As a third alternative you could use a Button for your ItemTemplate and pass the selected item as the CommandParameter
<Border BorderBrush="Red" BorderThickness="1">
<Button CommandParameter="{Binding }" ... />
</Border>
I can't give you an definite answer because I don't know your code base and what you're trying to do, but I hope this gives you enough information to give you a rough start and point you in the right direction for your situation.

Categories