Access wpf control from DataGrid DataTemplate - c#

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;
}
}
}
}

Related

how to import data from 2 tables to a datagrid(joined tables with foreign key)

I have 2 classes for my 2 Tables(User_Tbl.cs and RegFee_Tbl.cs),and my classes connected together with foreign key(above picture),here is(below pictures) my property of my RegFee_Tbl.sc and my User_Tbl.cs
and there is my datagrid(memebersDatagride is name of datagrid),I Bound 3 column of this datagrid for import data from RegFee_Tbl.cs and i bound 1 column of this datagrid to import data from User_Tbl.cs.and in my mainWindows.cs i use this method to load item from database to my datagrid,but i dont know how to import data from 2 different tables(tables connected together with FK) to a datagrid
that's my method for load item from my tables(MainWindows.cs):
public partial class Dashboard : UserControl
{
GymDbEntities db = new GymDbEntities();
public static DataGrid datagrid;
public Dashboard()
{
InitializeComponent();
Load();
}
private void Load()
{
membersdataGrid.ItemsSource = db.User_Tbl.ToList();
//membersdataGrid.ItemsSource = db.RegFee_Tbl.ToList();
datagrid = membersdataGrid;
}
and there is my datagrid in xaml:
<DataGrid Language="fa-IR" x:Name="membersdataGrid" RowStyle="{DynamicResource DataGridRowStyle1}" ColumnHeaderStyle="{DynamicResource DataGridColumnHeaderStyle1}" CellStyle="{DynamicResource DataGridCellStyle1}" Style="{DynamicResource DataGridStyle1}">
<DataGrid.Columns>
<!--bara eyjad sotone checkbox-->
<DataGridCheckBoxColumn CanUserResize="False" Width="auto" ElementStyle="{StaticResource CheckBoxStyle1}">
<DataGridCheckBoxColumn.HeaderTemplate>
<DataTemplate>
<CheckBox Style="{StaticResource CheckBoxStyle1}" />
</DataTemplate>
</DataGridCheckBoxColumn.HeaderTemplate>
</DataGridCheckBoxColumn>
<DataGridTextColumn Header="#" IsReadOnly="True" CanUserReorder="False" Width="auto" Binding="{Binding ID}"/>
<DataGridTemplateColumn Header="اعضا" IsReadOnly="True" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Border Width="25" Height="25" CornerRadius="50" Margin="0 0 10 0" Background="{Binding BgColor}">
<TextBlock Text="{Binding Character}" VerticalAlignment="Center" HorizontalAlignment="Center" Foreground="White" Margin="0 0 0 1"/>
</Border>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="نام پدر" IsReadOnly="True" Width="*" Binding="{Binding Fee}"/>
<DataGridTextColumn Header="شماره تماس" IsReadOnly="True" Width="*" Binding="{Binding NumberPhone}"/>
<DataGridTextColumn Header="آخرین واریزی" IsReadOnly="True" Width="*" Binding="{Binding FatherName}" />
<DataGridTemplateColumn Header="عملیات" IsReadOnly="True" Width="auto">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button x:Name="GridEditBtn" Style="{StaticResource gridEditbutton}">
<Icon:PackIconMaterial Kind="PencilBoxOutline" Style="{StaticResource gridButtonIcon}"/>
</Button>
<Button x:Name="GridRemoveBtn" Click="GridRemoveBtn_Click" Style="{StaticResource gridRemovebutton}" Margin="5 0 0 0" >
<Icon:PackIconMaterial Kind="DeleteOutline" Style="{StaticResource gridButtonIcon}" />
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
You are using Entity. So you have a Context (db) and each table is a list object. See code below.
GymDbEntities db = new GymDbEntities();
var results = (from u in db.User_Tbl
join r in db.RegFee_Tbl on u.NavigationProperties equal r.NavigationProperties
join s in sysdiagram on u.NavigationProperties equals s.NavigationProperties
select new { u = u, r = r, s = s}
).ToList();

Adding New Row to DataGrid on button click

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

How to add new stackpanel when new item added?

The problem that I'm facing is I want everytime user enter the item code all related details insert in a new stackpanel. that's means every item added will added a new stackpanel. 1 stackpanel will have 1 item. but I couldn't get how to do it that way.
this is the code behind when user key in barcode and press 'Enter'
private void txtItemCode_KeyDown(object sender, KeyEventArgs e)
{
try
{
string itemCode = txtItemCode.Text;
StackPanel spItemDisplay = new StackPanel();
spItemDisplay.Orientation = Orientation.Horizontal;
if (e.Key == Key.Return)
{
spItemDisplay.Children.Add(spItemDisplay);
SimpleItem item = cashierViewModel.validateItemOnHandCode(txtItemCode.Text, 1);
if (item != null)
{
cashierViewModel.AddItemToList(item, PosWindows2.cashier.ShopId);
LoadData();
dgItemDisplay.ItemsSource = null;
dgItemDisplay.ItemsSource = CashierViewModel.itemDisplayList;
}
else
{
MessageBox.Show("Item Not Available.", "Alert", MessageBoxButton.OK, MessageBoxImage.Information);
}
txtItemCode.Text = null;
}
}
this is at .xaml
<StackPanel x:Name="spItemDisplay" >
<ScrollViewer HorizontalAlignment="Right" >
<DataGrid CellEditEnding="DgItemDisplay_CellEditEnding" HorizontalAlignment="Center" Width="1036" Name="dgItemDisplay" AutoGenerateColumns="False" Height="auto" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" x:Name="dgItemCode" Width="200" Header="Barcode" Binding="{Binding ItemCode}" />
<DataGridTextColumn IsReadOnly="True" x:Name="dgItemName" Width="350" Header="Item Name" Binding="{Binding ItemName}" />
<DataGridTextColumn IsReadOnly="True" x:Name="dgItemPrice" Width="150" Header="Item Price" Binding="{Binding ItemPrice}" />
<DataGridTextColumn x:Name="dgQuantity" Width="150" Header="Quantity" Binding="{Binding Quantity, UpdateSourceTrigger=PropertyChanged}" />
<DataGridTextColumn x:Name="dgDiscount" Width="150" Header="Discount" Binding="{Binding Discount, UpdateSourceTrigger=PropertyChanged}" />
</DataGrid.Columns>
<DataGrid.RowDetailsTemplate>
<DataTemplate >
<StackPanel Name="spItem" HorizontalAlignment="Center" >
<Grid Margin="0,10" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="300" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Text="Quantity: " FontWeight="Bold" Grid.Column="2" Grid.Row="0"/>
<TextBox x:Name="txtQty" Text="{Binding Quantity, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.Row="0"/>
<TextBlock Text="Discount: " FontWeight="Bold" Grid.Column="2" Grid.Row="1"/>
<TextBox x:Name="txtDisc" Text="{Binding Discount, UpdateSourceTrigger=PropertyChanged}" Grid.Column="3" Grid.Row="1"/>
</Grid>
</StackPanel>
</DataTemplate>
</DataGrid.RowDetailsTemplate>
</DataGrid>
</ScrollViewer>
</StackPanel>
can anybody help ? I really need your help. Thank you :)
Can't you go for an ItemsControl/ListView, that has an StackPanel(for spItemDisplay) as an ItemsPanelTemplate and specify the DataTemplate as your StackPanel (spItem)?
Something along these lines:
<ItemsControl ItemsSource="{Binding DisplayItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel x:Name="spItem">
<Grid Margin="0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="Quantity: "/>
<TextBlock Text="{Binding Quantity}"/>
<TextBlock/>
</Grid>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
UPDATE:
If you're not familiar with DataTemplates please have a look at Andy's link in the comments or have a look at the following example.
Items Control + DataTemplate explained

Start edit in cell c# + wpf with telerik library

I need to implementation auto start begin edit cell in the same row and next column, after click in previous column.
In begin my table, code works correctly. But in the last row and in penultimate column code doesn't work correctly, it begin start edit in the last row and in third column.
But after how I write value by myself, code start to work correctly. I use telerik framework.
Thank you for your responses!
c#
var element = sender as FrameworkElement;
ConditionsRadGridView.CommitEdit();
var parentCell = element.GetVisualParent<GridViewCell>();
if (parentCell != null)
{
var index = ConditionsRadGridView.Columns.IndexOf(parentCell.Column);
if (index != -1 && index < parentCell.ParentRow.Cells.Count)
{
var nextCell = parentCell.ParentRow.Cells[index] as GridViewCell;
if (nextCell != null)
{
ConditionsRadGridView.CurrentCellInfo = new GridViewCellInfo(nextCell);
ConditionsRadGridView.BeginEdit();
}
}
}
part of wpf
<telerik:RadGridView ValidatesOnDataErrors="InViewMode"
Name="ConditionsRadGridView"
Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2"
Margin="6 3 6 6" HorizontalAlignment="Left"
RowIndicatorVisibility="Collapsed" AutoGenerateColumns="False"
CanUserDeleteRows="False" CanUserInsertRows="False" ShowGroupPanel="False" CanUserReorderColumns="False"
FrozenColumnCount="1"
CanUserFreezeColumns="False"
ItemsSource="{Binding Conditions}" EnableColumnVirtualization="False"
RowStyle="{StaticResource ValidationFixStyle}"
SelectionMode="Extended"
cal:Message.Attach="[Event PreviewKeyUp] = [Action ConditionsKeyUp($this.SelectedItems, $eventArgs)]">
<telerik:RadGridView.Columns>
<telerik:GridViewDataColumn CellStyle="{StaticResource SelectedCellStyle}" Header="{x:Static properties:Resources.Station}" DataMemberBinding="{Binding Name, Mode=TwoWay}"
CellTemplateSelector="{StaticResource ConditionNameTemplateSelector}"/>
<telerik:GridViewColumn IsVisible="{Binding IsHaveGroups}">
<telerik:GridViewColumn.CellTemplate>
<DataTemplate>
<CheckBox Visibility="{Binding IsGroup, Converter={StaticResource BoolToVisibilityConverter}}" IsChecked="{Binding IsSplitUp, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
cal:Message.Attach="[Event Click] = [Action IsSplitUpClick($datacontext)]" />
</DataTemplate>
</telerik:GridViewColumn.CellTemplate>
</telerik:GridViewColumn>
<telerik:GridViewDataColumn Header="{x:Static properties:Resources.AffinityOperator}" ColumnGroupName="Affinity"
DataMemberBinding="{Binding AffinityOperator, UpdateSourceTrigger=PropertyChanged}" TextAlignment="Center" IsReadOnly="True">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate DataType="{x:Type vm:StationConditionViewModel}">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<controls3:RadComboBox IsEnabled="{Binding IsRowEnabled}" SelectionChanged="StartEditNextCell"
SelectedItem="{Binding AffinityOperator, UpdateSourceTrigger=PropertyChanged}"
ItemsSource="{Binding Operators}" VerticalAlignment="Center" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>
<telerik:GridViewDataColumn Header="{x:Static properties:Resources.AffinityValue}" ColumnGroupName="Affinity" IsReadOnlyBinding="{Binding AffinityIsReadOnly}"
DataMemberBinding="{Binding Path=AffinityValue}" TextAlignment="Right">
<telerik:GridViewDataColumn.CellTemplate>
<DataTemplate DataType="{x:Type vm:StationConditionViewModel}">
<TextBlock Text="{Binding AffinityValue, StringFormat={}{0:N2}}" Visibility="{Binding AffinityVisibility}" VerticalAlignment="Center" HorizontalAlignment="Right" />
</DataTemplate>
</telerik:GridViewDataColumn.CellTemplate>
</telerik:GridViewDataColumn>

How to check all the checkboxes in body when header is checked

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.

Categories