Hi I have wpf application where in I have a datagrid with 3 check boxes in the header.
When any header checkbox is checked I want all the body checkboxes in that particular section to be checked.
Problem is when I check the header only the checkboxes that are visible in the view are checked. When I use the scroll bar and scroll down, the invisible checkboxes that are visible when scollbar is moved down, those check boxes are unchecked. Could anyone help. thanks. here is the code.
public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
// If there is a child found and if the child is of the T type.
//Dont remove null check . If no check i
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
private void ChkHeaderExtract_OnChecked(object sender, RoutedEventArgs e)
{
var extractCheckBoxes = GetAllCheckBoxs();
var i = 0;
foreach (var chk in extractCheckBoxes)
{
if (i % 3 == 0)
{
chk.IsChecked = true;
}
i++;
}
}
XAML:
<DataGrid x:Name="DgEntities" FrozenColumnCount="13" IsReadOnly="True" MaxWidth="854" Height="444" CanUserAddRows="false" ItemsSource="{Binding JobEntitiesCollectionViewSource.View, Mode=OneWay, NotifyOnTargetUpdated=True}" AutoGenerateColumns="False" SelectionMode="Single" SelectionUnit="FullRow" HorizontalScrollBarVisibility="Disabled" Margin="21,-49,106,5" Width="763">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" Header="Entity" Width="220" MinWidth="172" MaxWidth="215"/>
<DataGridTemplateColumn Header="Status" Width="138" MaxWidth="138" MinWidth="138">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Content="{Binding ExtractStatus, Mode=TwoWay, NotifyOnTargetUpdated=True}" Command="{Binding DataContext.HyperlinkCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}" CommandParameter="{Binding SelectedItem, ElementName=DgEntities}" Foreground="Blue" Cursor="Hand" MouseDoubleClick="Control_OnMouseDoubleClick" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock TextDecorations="Underline"><InlineUIContainer>
<ContentPresenter />
</InlineUIContainer></TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="40" MaxWidth="40" MinWidth="40">
<DataGridTemplateColumn.Header>
<CheckBox x:Name="ChkHeaderExtract" Checked="ChkHeaderExtract_OnChecked" Unchecked="ChkHeaderExtract_OnUnchecked"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox HorizontalAlignment="Center" Unchecked="ChkExtract_OnUnchecked" VerticalAlignment="Center" x:Name="chkExtract" IsChecked="{Binding ExtractIsSelected, Mode=TwoWay, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Status" Width="128" MaxWidth="128" MinWidth="128">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Content="{Binding TransformStatus, Mode=TwoWay, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}" Command="{Binding DataContext.HyperlinkCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" CommandParameter="{Binding SelectedItem, ElementName=DgEntities}" Cursor="Hand" Foreground="Blue" MouseDoubleClick="Control_OnMouseDoubleClick_2" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock TextDecorations="Underline"><InlineUIContainer>
<ContentPresenter />
</InlineUIContainer></TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="40" MaxWidth="40" MinWidth="40">
<DataGridTemplateColumn.Header>
<CheckBox x:Name="ChkHeaderTransform" Checked="ChkHeaderTransform_OnChecked" Unchecked="ChkHeaderTransform_OnUnchecked"/>
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox HorizontalAlignment="Center" Unchecked="ChkTransform_OnUnchecked" VerticalAlignment="Center" x:Name="chkTransform" IsChecked="{Binding TransformIsSelected, Mode=TwoWay, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Status" Width="137.5" MaxWidth="137.5" MinWidth="137.5">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Button Margin="5" Content="{Binding LoadStatus, Mode=TwoWay, NotifyOnTargetUpdated=True}" Command="{Binding DataContext.HyperlinkCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}" CommandParameter="{Binding SelectedItem, ElementName=DgEntities}" Cursor="Hand" Foreground="Blue" MouseDoubleClick="Control_OnMouseDoubleClick" >
<Button.Template>
<ControlTemplate TargetType="{x:Type Button}">
<TextBlock TextDecorations="Underline"><InlineUIContainer>
<ContentPresenter />
</InlineUIContainer></TextBlock>
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Width="56" MaxWidth="56" MinWidth="56">
<DataGridTemplateColumn.Header>
<CheckBox x:Name="ChkHeaderLoad" HorizontalAlignment="Center" Margin="0.3" Checked="ChkHeaderLoad_OnChecked" Unchecked="ChkHeaderLoad_OnUnchecked" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Margin="8" x:Name="chkLoad" Checked="ChkLoad_OnChecked" Unchecked="ChkLoad_OnUnchecked" IsChecked="{Binding LoadIsSelected, Mode=TwoWay, NotifyOnTargetUpdated=True, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
This will only return loaded children..
VisualTreeHelper.GetChildrenCount(depObj)
you should update the actual bound object and then refresh the itemssource really.
Related
I am new to WPF and got issues in adding new Row to Data-Grid on button click. I have tried few solutions but was not successful.
Tried-
If i enable "CanUserAddRows="True", This gives me buttons also which are present in upper rows. Also i dont want this approach as i want t add new row on button click.
I am attaching an image of how new row looks like if i use "CanUserAddRows="True"
<StackPanel Name="Decrypt_Vault">
<DataGrid x:Name="gdDecryptVault" HorizontalAlignment="Left" ColumnWidth="Auto" Margin="10,10,405,18" AutoGenerateColumns="False" HorizontalGridLinesBrush="LightGray" VerticalGridLinesBrush="LightGray">
<DataGrid.Columns>
<!--<DataGridTextColumn Header="Host" Binding="{Binding Path=Host}" Width="*" IsReadOnly="True" />-->
<DataGridTemplateColumn Header="Host">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Host}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=Host, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Header="Login" Binding="{Binding Path=Login}" Width="*" IsReadOnly="True" />-->
<DataGridTemplateColumn Header="Login">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Login}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=Login, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Header="Password" Binding="{Binding Path=Password}" Width="*" IsReadOnly="True"/>-->
<DataGridTemplateColumn Header="Password" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Name="LinePassword" Text="{Binding Path=Password}" Visibility="{Binding Path=IsPasswordVisible, Converter={StaticResource BoolToVis}}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=Password, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Password Actions" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<Button Click="bTogglePassword_Click" ToolTip="Toggle Password"
Name="bTogglePassword" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/button_login1.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
<Button Click="bCopyToClipBoard_Click" ToolTip="Copy Password to clipboard"
Name="bCopyToClipBoard" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/Copy_icon.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
</DockPanel>
<!--<TextBlock Text="{Binding Path=Password}"></TextBlock>-->
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Header="Items" Binding="{Binding Path=Project.Name}" Width="*" IsReadOnly="True"/>-->
<DataGridTemplateColumn Header="Items" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Project.Name}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=Project.Name, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Header="Created by" Binding="{Binding Path=CreatedBy}" Width="*" IsReadOnly="True"/>-->
<DataGridTemplateColumn Header="Created By" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=CreatedBy}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=CreatedBy, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--<DataGridTextColumn Header="Notes" Binding="{Binding Path=Notes}" Width="*" IsReadOnly="True"/>-->
<DataGridTemplateColumn Header="Notes" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=Notes}"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Background="Aquamarine" Text="{Binding Path=Notes, Mode=TwoWay, UpdateSourceTrigger=Explicit}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Actions" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DockPanel>
<!--<Button Content="Edit" Click="EditVaultLine"/>-->
<Button Click="EditVaultLine" ToolTip="Edit"
Name="Edit" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/edit.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
<Button Click="DeleteVaultLine" ToolTip="Delete"
Name="Delete" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/delete.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
</DockPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<DockPanel >
<Button Click="SaveEditedVaultLine" ToolTip="Save"
Name="Save" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/save2.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
<Button Click="CancelEditVaultLine" ToolTip="Cancel"
Name="Cancel" Visibility="Visible" Height="30" Width="30" >
<Image Source="/Images/erase.png" Stretch="Fill" Height="30" Width="30"/>
</Button>
</DockPanel>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
My .CS code to Bind data in Data-Grid
var result = weekTaskView.getVaultRecordLines();
List<VaultRecordLine> list = new List<VaultRecordLine>();
foreach (var item in result.Entities)
{
VaultRecordLine vrl = new VaultRecordLine();
if (item.Attributes.Contains("createdby"))
{
vrl.CreatedBy = item.Attributes["createdby"].ToString();
}
if (item.Attributes.Contains("new_account"))
{
vrl.Host = item.Attributes["new_account"].ToString();
}
if (item.Attributes.Contains("new_login"))
{
vrl.Login = item.Attributes["new_login"].ToString();
}
if (item.Attributes.Contains("new_password"))
{
vrl.Password = item.Attributes["new_password"].ToString();
}
if (item.Attributes.Contains("new_vaultid"))
{
vrl.Id = new Guid(item.Attributes["new_vaultid"].ToString());
}
list.Add(vrl);
}
gdDecryptVault.ItemsSource = list;
Requirement- When i click 'Add New Row button', i need a new row in EDITABLE mode so that user can fill up data. Also i need 'Save' and 'Cancel 'buttons at the end of row to save that data or to 'Cancel' it respectively.
I've made a small example-app to show you how you can add items to your DataGrid.
Your DataGrid should be bound to an ObservableCollection<T> where T is the type of your DataClass. The definition of your DataGrid then looks something like:
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Items}" CanUserAddRows="False">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Host" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center" Margin="4,2" Text="{Binding Host, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Login" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center" Margin="4,2" Text="{Binding Login, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Password" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock VerticalAlignment="Center" Margin="4,2" Text="{Binding Password, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Then you have a Button to add new rows to the ItemsSource of the DataGrid. The Button can look like:
<Button Grid.Row="1" Content="Add item" Command="{Binding AddItemCommand}"/>
In your c#-Code the AddItemCommand where the Command of your Button is bound to looks like:
private ICommand addItemCommand;
public ICommand AddItemCommand
{
get { return addItemCommand ?? (addItemCommand = new RelayCommand(AddItem)); }
}
private void AddItem(object obj)
{
Items.Add(new MyItem());
}
And the ObservableCollection<T> where the DataGrid is bound to looks like:
private ObservableCollection<MyItem> items;
public ObservableCollection<MyItem> Items
{
get { return items ?? (items = new ObservableCollection<MyItem>()); }
}
So now when you press the Button the AddItemCommand will be executed and this is adding a new Item to the ItemsSource of the DataGrid.
RelayCommand is an implementation of the ICommand-interface. So you don't have to use click-events. So you can uncouple your XAML-Definitions (View) from your C#-Logic (ViewModel). This is one important step to work with the MVVM-Pattern.
public class RelayCommand : ICommand
{
private readonly Action<object> execute;
private readonly Predicate<object> canExecute;
public RelayCommand(Action<object> execute, Predicate<object> canExecute = null)
{
if(execute == null)
throw new ArgumentException(nameof(execute));
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null || canExecute(parameter);
}
public void Execute(object parameter)
{
execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}
If you're new to WPF you should take a look at the MVVM-Pattern. It's really useful
I have a WPF DataGrid control, i also have a DataTemplate (CheckBox) control in it, which is shown below
<DataGridTemplateColumn Width="50" MinWidth="20" >
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<!--<TextBlock Text="Manage" FontSize="18" Foreground="#FF666666" HorizontalAlignment="Center" Margin="50,0" />-->
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" Margin="10,0,0,0" >
<CheckBox x:Name="chkBox_CheckAllStuRow" Width="20" Height="auto" Checked="chkBox_CheckAllStuRow_Checked" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" >
<CheckBox x:Name="chkBox_CheckStuRow" Width="20" Height="20" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="First Name" Width="*" MinWidth="100" Binding="{Binding f_name}" />
<DataGridTextColumn Header="Last Name" Width="*" MinWidth="100" Binding="{Binding l_name}" />
<DataGridTextColumn Header="Phone No" Width="*" MinWidth="100" Binding="{Binding phone}" />
<DataGridTemplateColumn Width="auto" MinWidth="250" >
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<TextBlock Text="Manage" FontSize="18" Foreground="#FF666666" HorizontalAlignment="Center" Margin="50,0" />
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" >
<Button x:Name="btn_ViewStu" Content="View" FontSize="14" HorizontalAlignment="Center" Height="27" Margin="3" Style="{DynamicResource ActiveButtonStyle}" Width="65" Click="btn_ViewStu_Click" />
<Button x:Name="btn_DeleteStu" Content="Delete" FontSize="14" HorizontalAlignment="Center" Height="27" Margin="3" Style="{DynamicResource DangerButtonStyle}" Width="65" Click="btn_DeleteStu_Click" />
<Button x:Name="btn_withDrwStu" Content="Withdraw" FontSize="14" HorizontalAlignment="Center" Height="27" Margin="3" Style="{DynamicResource DangerButtonStyle}" Width="70" />
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
What i want a achieve now, is to access the variable name of the check-box control, from my C# Code. Thanks in advance.
You can try this
List<string> chBoxName = new List<string>();
foreach (CheckBox tb in FindVisualChildren<CheckBox>(Window))
{
chBoxName.Add(tb.Name);
}
The chBoxName Property has all the Checkbox Names in the type of List<string>.
The Helper Method is
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
Ihave a textbox and a DataGrid. When I type in something in textbox, I want to filter the data in DataGrid.
I have done that with the below mentioned code:
In XAML:
<CollectionViewSource x:Key="GroupsViewSource" Source="{Binding Groups, UpdateSourceTrigger=PropertyChanged}" Filter="CollectionViewSource_Filter">
<CollectionViewSource.SortDescriptions>
<scm:SortDescription PropertyName="GroupName"/>
</CollectionViewSource.SortDescriptions>
</CollectionViewSource>
<DataGrid Grid.Row="5" Grid.Column="1" ItemsSource="{Binding Source={StaticResource GroupsViewSource}}"
SelectedItem="{Binding SelectedGroup}"
AutoGenerateColumns="False" CanUserAddRows="False"
SelectionMode="Single" SelectionUnit="FullRow"
EnableRowVirtualization="False" VirtualizingPanel.IsContainerVirtualizable="False" RowEditEnding="DataGrid_RowEditEnding">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Group Name" Width="*" SortMemberPath="GroupName">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding GroupName}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding GroupName}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Parent Group" Width="*" SortMemberPath="ParentID">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ParentID, Converter={StaticResource parentIDToGroupNameConverter}}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding Source={StaticResource ParentGroupsViewSource}}"
DisplayMemberPath="GroupName"
SelectedValue="{Binding ParentID, Converter={StaticResource parentIDToGroupNameConverter}}" SelectedValuePath="GroupName"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Edit" Width="50" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="btnEdit" Style="{StaticResource ResourceKey=EditButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityInverseConverter}}"
Click="EditSaveButton_Click"
Command="{Binding DataContext.EditCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
<Button x:Name="btnSave" Grid.Row="1" Style="{StaticResource ResourceKey=SaveButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityConverter}}"
Click="EditSaveButton_Click"
Command="{Binding DataContext.SaveCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Delete" Width="70" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Button x:Name="btnDelete" Style="{StaticResource ResourceKey=DeleteButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityInverseConverter}}"
Command="{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
<Button x:Name="btnCancel" Grid.Row="1" Style="{StaticResource ResourceKey=CancelButton}" Height="35" Width="35"
Visibility="{Binding DataContext.IsInEdit,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}},
Converter={StaticResource boolToVisibilityConverter}}"
Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"/>
</Grid>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<TextBox Grid.Column="0" Text="{Binding SearchGroupName, UpdateSourceTrigger=PropertyChanged}" />
In CodeBehind:
private void CollectionViewSource_Filter(object sender, FilterEventArgs e)
{
var a = e.Item.GetType().GetProperty("GroupName");
if (a != null)
{
if (_viewModel.SearchGroupName != "")
{
var s = a.GetValue(e.Item, null);
if (s != null)
e.Accepted = s.ToString().Contains(_viewModel.SearchGroupName, StringComparison.OrdinalIgnoreCase);
else
e.Accepted = false;
}
else
e.Accepted = true;
}
}
In ViewModel:
ERPLiteDBContext db = new ERPLiteDBContext();
public ListViewModel()
{
Groups = new ObservableCollection<Group>(db.Groups);
SearchGroupName = "";
}
private string _searchGroupName;
public string SearchGroupName
{
get
{
return _searchGroupName;
}
set
{
_searchGroupName = value;
OnPropertyChanged("SearchGroupName");
}
}
private ObservableCollection<Group> _groups;
public ObservableCollection<Group> Groups
{
get
{
return _groups;
}
set
{
_groups = value;
OnPropertyChanged("Groups");
}
}
The above code works. But for above code to work, I have to type-in something into the textBox, then click on the header of the DataGrid to sort it. So, in short above code does not provide live filtering. I would like to filter my data when I type-in something in TextBox......
So the filtering in your code is actually a follow-up from sorting. To perform filtering whenever you like, I suggest following, making small changes to your viewmodels:
Group knows wether itself should be filtered or not. It has a IsHidden property:
public class Group // actually a viewmodel
{
public bool IsHidden
{
get;
set;
}
public string Name
{
get;
set;
}
...
}
IsHidden is set for each member in the collection, each time the Text changes. The CollectionViewSource checks this property:
private void OnTextBoxTextChanged(object sender, TextChangedEventArgs e)
{
// reset first to keep continious filtering
Groups.ToList().ForEach(i => i.IsHidden = false);
foreach (var filteredGroup in Groups.Where(vm => vm.Name == _viewModel.SearchGroupName))
{
filteredGroup.IsHidden = true;
}
ICollectionView cv = CollectionViewSource.GetDefaultView(_dataGrid.ItemsSource);
if (cv != null)
{
// filter the Groups collection
cv.Filter = (vm as Group) => vm.IsHidden == false;
}
}
The regular DataGridCheckBoxColumn does not seem to allow commands so I decided to use DataGridTemplateColumn with a checkbox inside. The problem is my command is fired before the checkbox can be selected or deselected why is this happening?
my datGrid
<DataGrid x:Name="gridSpecifications" AutoGenerateColumns="False" ItemsSource="{Binding MyEntityList}">
<DataGrid.Resources>
<DataTemplate DataType="{x:Type DB:CoreNamedEntity}">
<TextBlock Text="{Binding Name}"></TextBlock>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Id" Width="auto" Binding="{Binding Path=Id}"></DataGridTextColumn>
<DataGridTemplateColumn Header="Description">
<DataGridTemplateColumn.CellTemplateSelector>
<TS:PhotometricTypeSelector
DataTemplateOne="{StaticResource PhantomNameTemplate}"
DataTemplateTwo="{StaticResource PhantomCountTemplate}">
</TS:PhotometricTypeSelector>
</DataGridTemplateColumn.CellTemplateSelector>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Hidden">
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Hidden}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.HideCommand}" CommandParameter="{Binding}"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding Hidden}" IsEnabled="False"></CheckBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
this is part of the commands code
private void HideCommandExecute(object param)
{
InputsAccessor inputsAccessor = new InputsAccessor();
var type = param.GetType();
int id;
string name = type.Name;
var ParamId = type.GetProperty("Id").GetValue(param, null);
bool ParamHidden = (bool)type.GetProperty("Hidden").GetValue(param, null);
id = (int)ParamId;
....
}
The IsChecked property must have UpdateSourceTrigger=PropertyChanged or it wont be set until after the command is called.
<CheckBox IsChecked="{Binding Hidden, UpdateSourceTrigger=PropertyChanged}"
CheckBox.Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.HideCommand}" CommandParameter="{Binding}"></CheckBox>
I have a DataGrid as follows:
<DataGrid CanUserAddRows="True" CanUserReorderColumns="False" CanUserSortColumns="False" CanUserDeleteRows="True"
ItemsSource="{Binding Groups}" AutoGenerateColumns="False">
<DataGrid.InputBindings>
<KeyBinding Key="Enter" Command="{Binding DataContext.NewRowCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}}}"/>
</DataGrid.InputBindings>
<DataGrid.Resources>
<CompositeCollection x:Key="Items">
<ComboBoxItem IsEnabled="False" Background="#FF2A2A2A" Foreground="White">
<Grid TextElement.FontWeight="Bold" >
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition Width="50" />
<ColumnDefinition SharedSizeGroup="B" />
</Grid.ColumnDefinitions>
<Grid.Children>
<TextBlock Grid.Column="0" Text="Group Name" />
<TextBlock Grid.Column="2" Text="Effect" />
</Grid.Children>
</Grid>
</ComboBoxItem>
<CollectionContainer Collection="{Binding Source={StaticResource GroupNamesWithCorrespondingEffectsCollection}}" />
</CompositeCollection>
<DataTemplate DataType="{x:Type helpers:GroupNameWithCorrespondingEffect}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A" />
<ColumnDefinition Width="50" />
<ColumnDefinition SharedSizeGroup="B" />
</Grid.ColumnDefinitions>
<Grid.Children>
<TextBlock Grid.Column="0" Text="{Binding GroupName}" />
<TextBlock Grid.Column="2" Text="{Binding CorrespondingEffect}" />
</Grid.Children>
</Grid>
</DataTemplate>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" Width="2*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Text="{Binding GroupName}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Group" Width="2*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{DynamicResource Items}"
SelectedValue="{Binding ParentID}"
SelectedValuePath="GroupID" Grid.IsSharedSizeScope="True" TextSearch.TextPath="GroupName">
</ComboBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Effect" Width="*" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ComboBox ItemsSource="{Binding DataContext.Effects, RelativeSource={RelativeSource AncestorType={x:Type Page}}}" DisplayMemberPath="Effect"
SelectedValue="{Binding EffectID}" SelectedValuePath="EffectID"
Visibility="{Binding Path=DataContext.SelectedGroupID,
RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Page}},
Converter={StaticResource effectsVisibilityConverter}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Here is my GroupsViewModel to which my Page's DataContext is Bound :
public class GroupsViewModel : ViewModelBase
{
public GroupsViewModel()
{
Groups = new ObservableCollection<Group>();
NewRowCommand = new RelayCommand(NewRow);
using (Entities db = new Entities())
{
List<GroupNameWithCorrespondingEffect> _GroupNamesWithCorrespondingEffects = (
from g in db.Groups
select new GroupNameWithCorrespondingEffect
{
GroupID = g.GroupID,
GroupName = g.GroupName,
CorrespondingEffect = g.Master_Effects.Effect
}
).ToList();
GroupNamesWithCorrespondingEffects
= new ObservableCollection<GroupNameWithCorrespondingEffect>(
_GroupNamesWithCorrespondingEffects.Where
(
u => !StaticMethods.GetAllChildren(25)
.Select(x => x.GroupID)
.Contains(u.GroupID)
).ToList()
);
Effects = new ObservableCollection<Master_Effects>(from m in db.Master_Effects
select m);
}
}
private ObservableCollection<Group> _groups;
public ObservableCollection<Group> Groups
{
get
{
return _groups;
}
set
{
_groups = value;
OnPropertyChanged("Groups");
}
}
public ICommand NewRowCommand { get; set; }
private void NewRow(object obj)
{
Groups.Add(new Group());
}
}
Problems :
I enter some data in the datagrid and then Press Enter a new row to the datagrid is added, which is expected. But new row is added to the top of the DataGrid instead I expect it to be added at last position. Also the data in other rows is cleared but I expect it to be as it is.
Is CanUserAddRows causing some confusion?
"When this property is set to true a blank row is displayed at the bottom of the DataGrid."
This row will always be underneath the rows provided by the ObservableCollection. I put some dummy data into NewRole like this:
var p = new Person() {Name = "New " + DateTime.Now.TimeOfDay.TotalMilliseconds};
People.Add(p);
to make the result a bit clearer. When you add a few rows the largest value of TotalMilliseconds will be at the end of the collection and will be the penultimate row in the DataGrid.
The culprit is your KeyBinding. According to your sample project, you never save the value that's in DataGrid back in the collection when you press Enter. It normally happens on lost focus, but since your Enter adds a row before focus is lost, you add a blank row into the empty collection.
DataGrid detects the change and updates the view with this new row, while preserving your changes that are in flight (the row where you pressed Enter hasn't finished updating). The result is obviously what you see.
I'm not sure why you're using Enter as KeyBinding to add row, when this should happen by itself? If it isn't happening it is because DataGrid isn't able to create your model (perhaps it's not public? or may be you don't have default parameterless ctor defined?)
For your sample project, I removed your KeyBinding & implemented INotifyChanged on your Person model and it works.
If you're using CellTemplates, you need to implement CellEditingTemplate as well.
<DataGrid CanUserAddRows="True" CanUserDeleteRows="True" CanUserReorderColumns="False" CanUserResizeColumns="False" AutoGenerateColumns="False" ItemsSource="{Binding People}">
<DataGrid.Columns>
<DataGridTemplateColumn Header="Name" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Name}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="Age" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Age}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding Age}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>