I managed to build a custom listbox where each item is loaded from a database showing in a stackpanel the name and the lastname. After these 2 textboxes there should be a button, which is correctly binded to an ICommand of the ViewModel.
The button correctly calls the right method, but it doesn't delete the selectedPerson because that object is null.
This is the WPF of the listbox
<Style x:Key="CustomHorizontalListbox" TargetType="{x:Type ListBox}">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel Orientation="Horizontal" Width="200" Margin="0,0,0,0">
<TextBox Text="{Binding FirstName}" Width="60" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<TextBox Text="{Binding LastName}" Width="100" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<Button Width="20" Height="20" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.OnDeletePatient}" CommandParameter="{Binding}"></Button>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
This is the relative method on the ViewModel
private void DeletePatient()
{
patientsManager.DeletePatient(SelectedPatient);
ListOfPatients = new ObservableCollection<RealPatient>(patientsManager.GetAllRealPatients());
SelectedPatient = null;
}
And this is how the custom listbox is included in the View
<ListBox Grid.Row="2" Grid.Column="3" Style="{StaticResource CustomHorizontalListbox}" ItemsSource="{Binding ListOfPatients}" SelectedItem="{Binding SelectedPatient}">
</ListBox>
So the problem is that the breakpoint at the DeleteMethod shows the SelectedPatient = null..
What do i miss?... Even when i click on the list item and not on the single button the SelectedPatient doesn't change
thanks
Here my full sample application that works:
<Window.Resources>
<Style x:Key="CustomHorizontalListbox" TargetType="{x:Type ListBox}">
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="2">
<StackPanel Orientation="Horizontal" Width="200" Margin="0,0,0,0">
<TextBox Text="{Binding FirstName}" Width="60" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<TextBox Text="{Binding LastName}" Width="100" BorderThickness="0" Margin="0" IsReadOnly="True"></TextBox>
<Button Width="20" Height="20" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBox}}, Path=DataContext.OnDeletePatient}" CommandParameter="{Binding}"></Button>
</StackPanel>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<WrapPanel></WrapPanel>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<Storyboard x:Key="OnGotKeyboardFocus1">
<BooleanAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0010000" Storyboard.TargetName="{x:Null}" Storyboard.TargetProperty="(Selector.IsSelected)">
<DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</Style.Resources>
<Style.Triggers>
<EventTrigger RoutedEvent="Keyboard.GotKeyboardFocus">
<BeginStoryboard Storyboard="{StaticResource OnGotKeyboardFocus1}"/>
</EventTrigger>
</Style.Triggers>
</Style>
</Window.Resources>
<Window.DataContext>
<Regions:ViewModel/>
</Window.DataContext>
<Grid>
<ListBox Style="{StaticResource CustomHorizontalListbox}" ItemsSource="{Binding ListOfPatients}" SelectedItem="{Binding SelectedPatient}" >
</ListBox>
</Grid>
Here the definition of my SelectedPatient property in the ViewModel:
private Patient _SelectedPatient;
public Patient SelectedPatient
{
get { return _SelectedPatient; }
set
{
_SelectedPatient = value;
NotifyPropertyChanged(m => m.SelectedPatient);
}
}
That will set your selected Item whenever you click in any place of your ListBox item row.
I wish I had a deeper explanation on why this works, but I found it in the MSDN forum:
http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/1642c5f9-e731-4a3d-9eed-0f574d90d925 I used that fix for the app I'm working with.
Related
In WPF, I'm trying to create a custom data grid that displays a cell as combobox when there is a databound list of data (a range for data), and a normal textbox if there isn't a limit. Additionally, i'm using the included validation for IDataErrorInfo and an MVVM pattern. Most of it works very well, but the devil is in the details. I'm seeing a problem where the validation on my combobox is not working as I expect it to.
I believe the issue I have is when I define both controls using a data trigger, but I'm not sure why it behaves the way it does. If I remove the validation on my textbox, the validation on the combobox works beautifully. When i put the properties back into the textbox to specify validation, the combobox validation no longer works.
Here is my xaml code on how to specify which control to use based on my data trigger:
<UserControl x:Class="GlobalVariableEditor.GlobalVariableEditorUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:viewmodel="clr-namespace:GlobalVariableEditor.ViewModel"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
xmlns:local="clr-namespace:GlobalVariableEditor"
xmlns:clr="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
d:DesignHeight="400" d:DesignWidth="500" Width="auto" Height="auto">
<UserControl.DataContext>
<viewmodel:GlobalVariableEditorViewModel x:Name="_GVEViewModel"/>
</UserControl.DataContext>
<UserControl.Resources>
<CollectionViewSource x:Key="VariablesViewSource" Source="{Binding VariablesData}">
</CollectionViewSource>
<Style x:Key="RangeStyleNormal" TargetType="ComboBox">
<Setter Property="HorizontalContentAlignment" Value="center"/>
<!--<EventSetter Event="SelectionChanged" Handler="ComboBox_SelectionChanged"></EventSetter>-->
<Setter Property="IsEditable" Value="False" />
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="IsTextSearchCaseSensitive" Value="True"/>
</Style>
</UserControl.Resources>
<GroupBox x:Name="grpGVEditor" Header="Global variable editor" FontSize="12">
<Grid x:Name="MainGrid">
<Grid.RowDefinitions>
<!--This is for any declarations or headers we may need for initial information (where to load xml file from, etc)-->
<RowDefinition x:Name="TopRowDefinition" Height="*" MinHeight="30" MaxHeight="50" />
<RowDefinition x:Name="RevisionRowDefinition" Height="*" MinHeight="30" MaxHeight="50" />
<!--this is where the data from the xml file should be populated to-->
<RowDefinition x:Name="DataRowDefinition" Height="*" MinHeight="200"/>
<!--this is where the buttons should be placed (cancel, apply, etc)-->
<!--<RowDefinition x:Name="FilterRowDefinition" Height="*" MinHeight ="25" MaxHeight="30"/>-->
<RowDefinition x:Name="ButtonRowDefinition" Height="*" MinHeight ="30" MaxHeight="50" />
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal">
<Label Height="30" Width="110" Content="XML file location: " BorderThickness="1" BorderBrush="Black" Margin="3,0,3,0"/>
<Label x:Name="lblCustomXMLFilePath" VerticalContentAlignment="Center" Height="30" Width="350" Content="{Binding FilePath}" BorderThickness="1" BorderBrush="Black" Margin="0,0,3,0" ToolTip="{Binding FilePath}" Background="Gray"/>
<!--<Button x:Name="btnLoad" Height="30" Width="50" Content="Load" Margin="0,5,5,5" Click="btnLoad_Click" Visibility="Hidden"/>-->
<Button Height="30" Width="50" Content="Revert" Margin="0,0,3,0" ToolTip="Revert to TP values" Visibility="Hidden"/>
</StackPanel>
<StackPanel Grid.Row="1" Orientation="Horizontal">
<Label Name="lblRevID" Height="30" Width="110" Content="File Revision ID: " BorderThickness="1" BorderBrush="Black" Margin="3,0,3,0"/>
<TextBox Name="txtRevID" Padding="3" Height="30" Width="100" VerticalContentAlignment="Center" TextAlignment="Left" BorderThickness="1" BorderBrush="Black" Margin="0,0,3,0" Text="{Binding FileVersion}" IsReadOnly="True" Background="Gray">
<TextBox.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding FileVersion}" Value="-1">
<Setter Property="TextBox.Background" Value="Salmon" />
<Setter Property="TextBox.ToolTip" Value="Invalid revision number. Settings file is in read-only mode." />
</DataTrigger>
<DataTrigger Binding="{Binding FileVersion}" Value="0">
<Setter Property="TextBox.Background" Value="Salmon" />
<Setter Property="TextBox.ToolTip" Value="Invalid revision number. Settings file is in read-only mode." />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
<TextBox x:Name="tbDummy" Visibility="Hidden"></TextBox>
</StackPanel>
<DockPanel Grid.Row="2" HorizontalAlignment="Stretch" MinHeight="200" Margin="0,5,0,0">
<DataGrid x:Name="PropertyGrid" SelectionMode="Single" SelectionUnit="Cell" RowHeaderWidth="0" IsTextSearchCaseSensitive="True" GridLinesVisibility="All"
AutoGenerateColumns="False" AlternationCount="2" ItemsSource="{Binding FilteredGridEntries}" Margin="3,0,0,0">
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent"/>
</Style.Resources>
<Setter Property="IsEnabled" Value="{Binding HasWriteAccess}" ></Setter>
<Style.Triggers>
<Trigger Property="AlternationIndex" Value="0">
<Setter Property="Background" Value="White" />
</Trigger>
<Trigger Property="AlternationIndex" Value="1">
<Setter Property="Background" Value="WhiteSmoke" />
</Trigger>
<MultiDataTrigger >
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding IsReadOnly}" Value="True"/>
<Condition Binding="{Binding IsChecked, ElementName=_cboShowAll}" Value="False"/>
</MultiDataTrigger.Conditions>
<MultiDataTrigger.Setters>
<Setter Property="Visibility" Value="Collapsed"/>
</MultiDataTrigger.Setters>
</MultiDataTrigger>
<DataTrigger Binding="{Binding IsReadOnly}" Value="True">
<Setter Property="Background" Value="Gray"/>
<Setter Property="IsEnabled" Value="False" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Resources>
<Style x:Name="CenterContent" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="ToolTip" Value="{Binding Column.(ToolTipService.ToolTip), RelativeSource={RelativeSource Self}}"/>
</Trigger>
</Style.Triggers>
</Style>
<Image x:Name="rowHeaderImage"
x:Key="rowHeaderTemplate"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Width="64"
Margin="1,0">
<Image.Style>
<Style TargetType="Image">
<Style.Triggers>
<DataTrigger Binding="{Binding IsReadOnly}" Value="true">
<Setter Property="Source" Value="/Resources/access.ico"/>
</DataTrigger >
<DataTrigger Binding="{Binding IsReadOnly}" Value="false">
<Setter Property="Source" Value="/Resources/no_access.jpg"/>
</DataTrigger >
</Style.Triggers>
</Style>
</Image.Style>
</Image>
</DataGrid.Resources>
<DataGrid.ItemBindingGroup>
<BindingGroup/>
</DataGrid.ItemBindingGroup>
<DataGrid.Columns>
<!--This is the Name column-->
<DataGridTemplateColumn Header="Name" ToolTipService.ToolTip="Global variable name/ID" MinWidth ="200" Width="2*">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Gray"></Setter>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding Name}" IsReadOnly="True" Background="Transparent" ToolTip="{Binding Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--This is the Site column-->
<!--<DataGridTemplateColumn Header="Site" ToolTipService.ToolTip="Site" Width="1*" MaxWidth ="30" IsReadOnly="False" Visibility="Hidden">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox TextAlignment="Center" Text="{Binding Site, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="{Binding IsReadOnly}" Background="Transparent"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<!--This is the Slot column-->
<!--<DataGridTemplateColumn Header="Slot" ToolTipService.ToolTip="Slot" Width="1*" MaxWidth ="30" IsReadOnly="False" Visibility="Hidden">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox TextAlignment="Center" Text="{Binding Slot, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="{Binding IsReadOnly}" Background="Transparent"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<!--This is the High Limit column-->
<!--<DataGridTemplateColumn Header="High Limit" ToolTipService.ToolTip="High limit" MaxWidth="125" Width="1*" Visibility="Hidden">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox TextAlignment="Center" Text="{Binding HiLimit, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="{Binding IsReadOnly}" Background="Transparent"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<!--This is the Low Limit column-->
<DataGridTemplateColumn Header="Value" MinWidth="200" ToolTipService.ToolTip="Global variable programmed value" Width="3*">
<DataGridTemplateColumn.HeaderStyle>
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment"
Value="Center" />
</Style>
</DataGridTemplateColumn.HeaderStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<!--By default, allow the user to free edit the combobox.
This allows backwards compatibility with existing TP settings-->
<ContentControl Content="{Binding}">
<ContentControl.Style>
<Style TargetType="ContentControl">
<Style.Triggers>
<DataTrigger Binding="{Binding HasRange}" Value="true">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<ComboBox
ItemsSource="{Binding Range, Mode=OneWay}"
MinWidth="50"
Text="{Binding ProgrammedValue,
UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True}"
Style="{StaticResource RangeStyleNormal}"
Width="auto" >
</ComboBox>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
<DataTrigger Binding="{Binding HasRange}" Value="false">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBox
HorizontalAlignment="Stretch"
Background="Transparent"
BorderThickness="0"
MinWidth="50"
Text="{Binding ProgrammedValue, Mode=TwoWay,
UpdateSourceTrigger=LostFocus,
ValidatesOnDataErrors=True,
NotifyOnValidationError=True
}"
TextAlignment="Center"
Width="Auto">
</TextBox>
</DataTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
</ContentControl>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--This is the Low Limit column-->
<!--<DataGridTemplateColumn Header="Low Limit" ToolTipService.ToolTip="Lower limit" Width="1*" MaxWidth="125" Visibility="Hidden">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox TextAlignment="Center" Text="{Binding LowLimit, Mode=TwoWay, UpdateSourceTrigger=LostFocus}" IsReadOnly="{Binding IsReadOnly}" Background="Transparent"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>-->
<!--This is the Fleet column-->
<DataGridTemplateColumn Header="Fleet Variable" ToolTipService.ToolTip="Global variable scope" MinWidth ="75" Width="1*">
<DataGridTemplateColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Gray"></Setter>
</Style>
</DataGridTemplateColumn.CellStyle>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding IsFleet}" IsReadOnly="True" Background="Transparent" ToolTip="{Binding IsFleet}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--<DataGridCheckBoxColumn Header="Is fleet" Width="1*" MinWidth="50" ToolTipService.ToolTip="Variable of fleet scope" Binding="{Binding IsFleet}" IsReadOnly="True">
</DataGridCheckBoxColumn>-->
</DataGrid.Columns>
</DataGrid>
</DockPanel>
<!--These are the buttons at the bottom of the control-->
<Grid Grid.Row="3">
<StackPanel Height="40" Orientation="Horizontal" VerticalAlignment="Center" Margin="0,2" Width="auto">
<Label Height="25" HorizontalAlignment="Left" Width="40" Margin="5,2,3,0">Filter:</Label>
<TextBox x:Name="_tboFilter" HorizontalAlignment="Left" Height="25" Margin="0,3,0,0" Width="200" MaxLength="40" MaxLines="1" MinLines="1" AcceptsTab="True" TextAlignment="Left" Text="{Binding FilterString, UpdateSourceTrigger=PropertyChanged}" />
<CheckBox Name="_cboShowAll" HorizontalAlignment="Left" Height="25" IsChecked="False" Margin="15,7,0,0">
<TextBlock Text="Show all" />
</CheckBox>
</StackPanel>
<StackPanel Height="40" Width="auto" Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,2">
<Button x:Name="btnTestError" HorizontalAlignment="Right" Height="25" Width="60" Content="TestError" ToolTip="Fire error events for logging" Margin="0,0,3,0" Command="{Binding TestErrorButtonCommand}" Visibility="{Binding EnableQADebuggingTools}" />
<!--<Button x:Name="btnApply" Height="25" Width="50" Content="Apply" ToolTip="Apply changes" Margin="0,3,3,0" Click="btnApply_Click" IsEnabled="{Binding HasDataChanged}" />-->
<Button x:Name="btnApply" HorizontalAlignment="Right" Height="25" Width="50" Content="Apply" ToolTip="Apply changes" Margin="0,0,3,0" Command="{Binding ApplyChangesButtonCommand}" >
<Button.Style>
<Style TargetType="Button">
<Setter Property="IsEnabled" Value="False"/>
<Style.Triggers>
<!-- Button enabled if the following conditions is met: HasDataChanged is true -->
<MultiDataTrigger>
<MultiDataTrigger.Conditions>
<Condition Binding="{Binding HasDataChanged}" Value="True"/>
<Condition Binding="{Binding HasWriteAccess}" Value="True"/>
</MultiDataTrigger.Conditions>
<Setter Property="IsEnabled" Value="True"/>
</MultiDataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
<!--<Button x:Name="btnCancel" Height="25" Width="50" Content="Cancel" Margin="0,3,3,0" ToolTip="Revert to TP values" Click="btnCancel_Click" Command="{Binding CancelButtonCommand}"/>-->
<Button x:Name="btnCancel" HorizontalAlignment="Right" Height="25" Width="50" Content="Cancel" Margin="0,0,3,0" ToolTip="Revert to TP values" Click="btnCancel_Click"/>
</StackPanel>
</Grid>
</Grid>
</GroupBox>
</UserControl>
IDataErrorInfo is implemented thusly:
public string this[string columnName]
{
get
{
string result = null;
try
{
if (columnName == "ProgrammedValue")
{
//Validation routine: data can not be empty field.
if (this.HasRange)
{
// This is a combobox
if (ProgrammedValue == null)
{
result = "Field must have selection";
}
else
{
if (Range != null && !Range.Contains(ProgrammedValue) )
{
result = "Field must have selection";
}
}
}
else
{
// This is a text box:
if (string.IsNullOrEmpty(ProgrammedValue))
{
result = "Field can not be empty.";
}
}
}
}
catch (Exception ex)
{
// Eat the exception.. really should never get here, but if there is an exception
result = null;
}
return result;
}
}
In my model, the bound properties are defined:
public string ProgrammedValue
{
get
{
return _programmedValue;
}
set
{
_programmedValue = value;
RaisePropertyChanged("ProgrammedLimit");
}
}
public List<string> Range
{
get
{
return _range;
}
set
{
_range = value;
RaisePropertyChanged("Range");
}
}
public bool HasRange
{
get
{
return _hasRange;
}
set
{
_hasRange = value;
RaisePropertyChanged("HasRange");
}
}
RangeStyleNormal definition:
<UserControl.Resources>
<Style x:Key="RangeStyleNormal" TargetType="ComboBox">
<Setter Property="HorizontalContentAlignment" Value="center"/>
<EventSetter Event="SelectionChanged" Handler="ComboBox_SelectionChanged"></EventSetter>
<Setter Property="IsEditable" Value="False" />
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="IsTextSearchCaseSensitive" Value="True"/>
</Style>
</UserControl.Resources>
As previously stated, when I remove ValidatesOnDataErrors and NotifyOnValidationError from the textbox properties, the combobox works like a charm. I know that the validation routine I have specified works correctly. I'm hoping someone here can see some obvious coding error(s) I've made and explain what I did wrong and how to correct it. Thanks in advance.
I was looking a while for how to build a list item with a check mark if selected.
Checking different Resources, it seems there are a lot of code solutions, bot no true XAML only one.
So this is what i tried to achive:
Any additions are welcomed.
In the spirit of Answer-your-own (Stackoverflow blog)
So here is what I actually got after hours of figuring it out.
As said, any additions are welcomed.
The check mark is:
U+2714 (10004) ✔ HEAVY CHECK MARK Dingbats (2700–27BF)
The style code:
basically creating a wrapper for any item, setting base properties, and changing them on item selection, made available as StaticResource as checkmarkItem
<Window.Resources>
<Style x:Key="checkmarkItem" TargetType="ListBoxItem">
<Setter Property="SnapsToDevicePixels" Value="true"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="Border" Background="Transparent" BorderThickness="5" BorderBrush="Transparent" Margin="0,1,0,1">
<Grid>
<TextBlock VerticalAlignment="Top" HorizontalAlignment="Right" Name="Marker" Visibility="Hidden" Background="#0078D7" Padding="5,0,0,5" Foreground="White">✔</TextBlock>
<ContentPresenter />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="ListBoxItem.IsSelected" Value="true">
<Setter TargetName="Marker" Property="Visibility" Value="Visible" />
<Setter TargetName="Border" Property="BorderBrush" Value="#0078D7"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
The implementation:
it is just a regular stackpanel arrangement, all styles are added by referring in ItemContainerStyle="{StaticResource checkmarkItem}"
<Grid>
<Label Grid.Row="0" FontSize="26">Software</Label>
<ListView Grid.Row="1" SelectionMode="Multiple" BorderBrush="Transparent" ItemContainerStyle="{StaticResource checkmarkItem}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="64" AutomationProperties.Name="{Binding Title}">
<Image Source="{Binding Icon}" Height="48" Width="48" VerticalAlignment="Center" Margin="5,0,20,0"/>
<StackPanel Orientation="Vertical" VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontSize="16" TextWrapping="Wrap"/>
<TextBlock Text="{Binding Description}" TextWrapping="Wrap" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
<ListView x:Name="CustomWorkoutListView" ItemsSource="{Binding WorkoutTypeDTO}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto" Style="{DynamicResource ListViewStyle1}" Width="400" Height="119" SelectionChanged="CustomWorkoutSelectionChanged">
<ListView.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Margin" Value="0"/>
<Setter Property="Padding" Value="0"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<StackPanel>
<StackPanel Margin="0,0,10,8" Name="WorkoutTypeBackground" Visibility="{Binding IsEditable,Converter={StaticResource NegBooleanToVisibilityConverter}}">
<StackPanel.Background>
<ImageBrush ImageSource="/Assets/Images/workout_type_back_unselected.png"/>
</StackPanel.Background>
<TextBlock Name="TextBlockName" Text="{Binding WorkoutTypeName}" Style="{StaticResource WorkoutTypeNameText}"/>
</StackPanel>
<StackPanel Margin="0,0,10,8" Orientation="Horizontal" Visibility="{Binding IsEditable,Converter={StaticResource BooleanToVisibilityConverter}}">
<StackPanel.Background>
<ImageBrush ImageSource="/Assets/Images/workout_type_back_edit.png"/>
</StackPanel.Background>
<TextBlock Text="{Binding WorkoutTypeName}" Style="{StaticResource WorkoutTypeNameText}"/>
<Button BorderThickness="0" Template="{DynamicResource ButtonBaseControlTemplate1}" Name="CrossButton" Width="20" Height="20" Click="DeleteWorkoutType">
<Button.Background>
<ImageBrush ImageSource="/Assets/Images/workout_type_X.png"/>
</Button.Background>
</Button>
</StackPanel>
</StackPanel>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="WorkoutTypeBackground" Property="Background">
<Setter.Value>
<ImageBrush ImageSource="/Assets/Images/workout_type_back_selected.png"/>
</Setter.Value>
</Setter>
<Setter TargetName="TextBlockName" Property="FontSize" Value="48"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListView.ItemsPanel>
</ListView>
In the above code, the listviewitems consists of Stackpanel which itself has a textblock and a button. Now when i click the button, how would i know which listviewitem is clicked so that i can do some manipulation?
If you want to handle this in codebehind, then you can use VisualTreeHelper to get to the parent of the Button clicked. You can use the method below to get to ti
public T GetParent<T>(DependencyObject child) where T : DependencyObject
{
var parent = VisualTreeHelper.GetParent(child);
if(parent != null)
{
if(parent is T)
{
return parent as T;
}
return GetParent<T>(parent);
}
else
{
return null;
}
}
and from Button Click hanlder, you can call
ListViewItem item = GetParent<ListViewItem>(sender);
and item.DataContext will give you the Data backing your item.
But i will suggest you to handle this MVVM way, by defining the Command in your ViewModel and send the current item as its CommandParameter
<Button Command="{Binding DataContext.MyCommand, RelativeSource={RelativeSource AncestorType={x:Type ListView}}}" CommandParameter="{Binding}" BorderThickness="0" Template="{DynamicResource ButtonBaseControlTemplate1}" Name="CrossButton" Width="20" Height="20" Click="DeleteWorkoutType">
This will give you the current item backing your ListViewItem in your command handler
I'm using the WPF Toolkit for a .Net 4.0 application written in C#. I have a Chart containing a Column Series bound to a dictionary. The chart works fine but I'd like to show the actual value of each column, either in a textbox below each column, in the middle of each column, or on top of each column. I've been searching for a while and haven't been able to find any information on this. I set up a style for the chart as well as the ColumnSeries, but have not made any progress yet. Any suggestions?
My Chart xaml is:
xmlns:DV="clr-namespace:System.Windows.Controls.DataVisualization;assembly=System.Windows.Controls.DataVisualization.Toolkit"
xmlns:DVC="clr-namespace:System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit"
...
<Page.Resources>
<Style x:Key="MyChart" TargetType="DVC:Chart">
<Setter Property="PlotAreaStyle">
<Setter.Value>
<Style TargetType="Grid">
<Setter Property="Background" Value="#FF2D2D30" />
</Style>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="NoLegend" TargetType="DV:Legend">
<Setter Property="Visibility" Value="Hidden" />
<Setter Property="Width" Value="0" />
</Style>
<Style x:Key="ColumnSeriesStyle" TargetType="{x:Type DVC:ColumnSeries}">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DVC:ColumnSeries}">
<Canvas x:Name="PlotArea" Visibility="Visible">
<TextBox Text="{Binding Path=Value.Value}" IsReadOnly="True"/>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
...
<DVC:Chart Name="TempChart" Style="{StaticResource MyChart}" LegendStyle="{StaticResource NoLegend}">
<DVC:Chart.Series>
<DVC:ColumnSeries IndependentValueBinding="{Binding Path=Value.Value}"
DepdendentValueBinding="{Binding Path=Value.Value}"
ToolTip="{Binding Path=Value.Value}"
Style="{StaticResource ColumnSeriesStyle}">
<DVC:ColumnSeries.DependentRangeAxis>
<DVC:LinearAxis x:Name="TempYAxis"
</DVC:ColumnSeries.DependentRangeAxis>
</DVC:Chart.Series>
</DVC:Chart>
I managed to style my ColumnSeries with this:
<Style x:Key="ColumnSeriesStyle" TargetType="{x:Type DVC:ColumnSeries}">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DVC:ColumnSeries}">
<Canvas x:Name="PlotArea" Visibility="Visible">
<!-- Actual Values -->
<ListBox x:Name="ActualValueListBox" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch"
Background="{StaticResource WindowBackground}" Foreground="#FFBB702F" BorderBrush="#FF2D2D30" ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<TextBox HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center" FontSize="12"
Foreground="{StaticResource ValueForeground}" Background="{StaticResource ValueBackground}" Width="40"
Text="{Binding Path=Value.Value}" />
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Rows="1" Height="20"
Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DVC:ColumnSeries}}, Path=ActualWidth}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Canvas>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I've got a data template for a list box item similar to the one on this page...
link
I would like to take it a step further and do something to highlight the items when they change. For example, using the code in the link above, I would like to put a trigger to do something when Widget.Quantity changes. Maybe make the quiantity item (nothing else) flash or something. How can I do that? I include the relevant code below...
<Window.Resources>
<Style x:Key="RoundedItem" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border CornerRadius="10" BorderBrush="Black" BorderThickness="1" Margin="1">
<ContentPresenter />
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate DataType="{x:Type local:Widget}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Name}" />
<Label Content="{Binding Quantity}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<ListBox ItemsSource="{Binding Widgets}" ItemContainerStyle="{StaticResource RoundedItem}" HorizontalContentAlignment="Stretch" />
Just add triggers to the DataTemplate.Triggers collection.
<DataTemplate DataType="{x:Type local:Widget}">
<StackPanel x:Name="panel" Orientation="Horizontal">
<Label Content="{Binding Name}" />
<Label Content="{Binding Quantity}" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding SomeProperty}" Value="True">
<Setter Property="Background" Value="Yellow" TargetName="panel" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
You'll probably want to add a property in your Widget class to do that. Or if Widget is a Model, you may want to wrap it in a WidgetViewModel class with an "IsFlashing" property on it. Then set the trigger to fire whenever this "IsFlashing" property is True.
I've managed to get it working with EventTriggers. Complete code below. In summary, the event trigger detects when the bound value changes, then turns the text orange briefly.
<UserControl.Resources>
<!-- instantiate an instance of the TimeSettingsCollection class -->
<c:TimeSettingsCollection x:Key="TimeSettingsCollection"/>
<Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="ItemBorder" BorderBrush="Gray" BorderThickness="1" Margin="3" Padding="7" Background="Transparent">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="ItemBorder" Property="Background" Value="LightBlue" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<DataTemplate DataType="{x:Type c:TimeSettingsItem}">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="0" Margin="0,0,8,0"
Style="{StaticResource smallTitleStyle}">Pc Name:</TextBlock>
<TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Path=PcName}"
Style="{StaticResource textStyleTextBlock}"/>
<TextBlock Grid.Row="1" Grid.Column="0" Margin="0,0,8,0"
Style="{StaticResource smallTitleStyle}">Time:</TextBlock>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding Path=TimeSettings.DateTime, NotifyOnTargetUpdated=True}"
Style="{StaticResource textStyleTextBlock}" x:Name="timeTextBlock">
<TextBlock.Background>
<SolidColorBrush Color="Transparent"/>
</TextBlock.Background>
<TextBlock.Triggers>
<EventTrigger RoutedEvent="Binding.TargetUpdated">
<BeginStoryboard>
<Storyboard>
<ColorAnimation
Storyboard.TargetName="timeTextBlock"
Storyboard.TargetProperty="(TextBlock.Foreground).(SolidColorBrush.Color)"
To="Orange"
Duration="0:0:1"
AutoReverse="True"/>
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</TextBlock.Triggers>
</TextBlock>
</Grid>
</DataTemplate>
</UserControl.Resources>
<DockPanel>
<ListBox Name="timeListBox" ItemsSource="{Binding Source={StaticResource TimeSettingsCollection}}" ItemContainerStyle="{StaticResource ListBoxItemStyle}" HorizontalContentAlignment="Stretch" IsSynchronizedWithCurrentItem="True">
</ListBox>
</DockPanel>