Wpf ScrollIntoView not working first time - c#

I have a ListView include Expander, and I assign a SelectedIndex, then call ScrollIntoView to SelectedItem position. (It can auto expand.)
lv_SelectionChanged was invoke every times.
private void lv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
foreach (Expander exp in FindVisualChildren<Expander>(lv.lv))
{
var a = (exp.Header as StackPanel).Children[0] as TextBlock;
if (a.Text.Equals((lv.lv.SelectedItem as User).group))
exp.IsExpanded = true;
}
lv.ScrollIntoView(lv.SelectedItem);
}
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;
}
}
}
}
But, it was not working at first time. (If it's a simple ListView, it work!)
I have no idea.
Thx.
xaml
<UserControl.Resources>
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
<Style x:Key="GroupHeaderStyle" TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<!--<Expander IsExpanded="{Binding Mode=TwoWay, Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListViewItem}, Mode=FindAncestor}}" MouseRightButtonDown="Expander_MouseRightButtonDown">-->
<Expander IsExpanded="False" MouseRightButtonDown="Expander_MouseRightButtonDown">
<Expander.Header>
<StackPanel Orientation="Horizontal">
<StackPanel.ContextMenu>
<ContextMenu>
<MenuItem Name="mi_ExpandAll" Header="Hide Age column" Click="mi_ExpandAll_Click"/>
<MenuItem Name="mi_CollapseAll" Header="None"/>
</ContextMenu>
</StackPanel.ContextMenu>
<TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="Gray" FontSize="16" VerticalAlignment="Bottom"/>
<TextBlock Text="{Binding ItemCount}" FontSize="22" Foreground="Green" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
<TextBlock Text=" item(s)" FontSize="22" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
</StackPanel>
</Expander.Header>
<ItemsPresenter>
<ItemsPresenter.ContextMenu>
<ContextMenu>
<MenuItem Header="Add Item" Click="MenuItem_Click"/>
<MenuItem Header="Menu Item 2">
<MenuItem Header="Remove Item" Click="MenuItem_Click_1"></MenuItem>
<MenuItem Header="Select last Item" Click="MenuItem_Click_2"></MenuItem>
</MenuItem>
</ContextMenu>
</ItemsPresenter.ContextMenu>
</ItemsPresenter>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Resources>
<ListView Margin="10" Name="lv" Grid.Row="0" ItemsSource="{Binding GroupView}" SelectedIndex="{Binding Index}" SelectedItem="{Binding Item}" SelectionChanged="lv_SelectionChanged">
<ListView.View>
<GridView>
<local:GridViewColumnExt Header="Name" Width="120" DisplayMemberBinding="{Binding Name}"/>
<local:GridViewColumnExt x:Name="colAge" Header="Age" Width="50">
<local:GridViewColumnExt.CellTemplate>
<DataTemplate>
<Button Content="{Binding Age}"></Button>
</DataTemplate>
</local:GridViewColumnExt.CellTemplate>
</local:GridViewColumnExt>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle ContainerStyle="{StaticResource GroupHeaderStyle}">
</GroupStyle>
</ListView.GroupStyle>
</ListView>
I set SelectedIndex in event
private void MenuItem_Click_2(object sender, RoutedEventArgs e)
{
lv.SelectedIndex = 8;
}
Edit
I try to set IsExpanded="True", then it is work. So, if IsExpanded="False" at first, can't it scrolling?

I user expander.BringIntoView(), then it's work!

Related

C# WPF Tab Navigate to control inside of a ListBoxItem from outside of ListBox

I have a window with version text boxes, buttons, and a ListBoxthat expands and contracts. Each ListBox item has multiple text boxes. I am trying to find a way to tab navigate from outside of the the ListBoxto the first TextBox in the first item for the ListBox. I can get it to navigate to the ListBox itself and if I hit the down arrow key it will select the first item but that is clumsy. I need it to tab directly from something outside the ListBox to something inside the ListBox.
Below is some of the XAML I use for the ListBox.
<ListBox x:Name="add_users_listbox" Margin="2,116,-8,0" BorderThickness="0" Height="322" Padding="0,0,0,0"
HorizontalContentAlignment="Center" VerticalContentAlignment="Top"
HorizontalAlignment="Center" VerticalAlignment="Top"
SelectionMode="Single"
IsTabStop="True"
TabIndex="1004"
Background="{x:Null}" BorderBrush="{x:Null}"
ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="False"
ItemsSource="{Binding Add_User_Binding}"
SelectedIndex="{Binding Add_User_Selected_Index, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ListBox.Resources>
<Style TargetType="{x:Type ScrollBar}" BasedOn="{StaticResource ScrollBar_Rounded}"/>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource CustomListBoxItemStyle}"/>
<Style TargetType="{x:Type ListBox}" >
<Setter Property="KeyboardNavigation.TabNavigation" Value="Continue" />
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="60" Background="Transparent"
HorizontalAlignment="Center" VerticalAlignment="Top">
<TextBox Height="26" Width="102" Padding="0,-1,0,1" Margin="2,2,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top" HorizontalContentAlignment="Left" VerticalContentAlignment="Center"
FontFamily="Segoe UI" FontSize="16" FontWeight="Bold"
TextWrapping="NoWrap" IsReadOnlyCaretVisible="True" UndoLimit="10" AllowDrop="False" MaxLines="1"
TabIndex="{Binding First_TabIndex}"
MaxLength="20"
TextChanged="first_last_textbox_TextChanged"
PreviewTextInput="first_last_textbox_PreviewTextInput"
Text="{Binding First_Textbox, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay, ValidatesOnDataErrors=True}">
</TextBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Simply make your ListBox IsTabStop="False" and the LitBoxItemStyle too.
I added this setter to the ListBoxItemStyle: <Setter Property="IsTabStop" Value="False"/>
<ListBox x:Name="add_users_listbox" Grid.Row="1" BorderThickness="0" Height="322" Padding="0,0,0,0"
HorizontalContentAlignment="Center" VerticalContentAlignment="Top"
HorizontalAlignment="Center" VerticalAlignment="Top"
SelectionMode="Single"
IsTabStop="False"
TabIndex="1004"
Background="{x:Null}" BorderBrush="{x:Null}"
ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Disabled"
ScrollViewer.CanContentScroll="False"
ItemsSource="{Binding Add_User_Binding}"
SelectedIndex="{Binding Add_User_Selected_Index, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}">
<ListBox.Resources>
<Style TargetType="{x:Type ScrollBar} BasedOn="{StaticResource ScrollBar_Rounded}" "/>
<Style TargetType="{x:Type ListBoxItem}" BasedOn="{StaticResource CustomListBoxItemStyle}">
<Setter Property="IsTabStop" Value="False"/>
</Style>
<Style TargetType="{x:Type ListBox}" >
<Setter Property="KeyboardNavigation.TabNavigation" Value="Continue" />
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="60" Background="Transparent"
HorizontalAlignment="Center" VerticalAlignment="Top">
<TextBox Height="26" Width="102" Padding="0,-1,0,1" Margin="2,2,0,0"
HorizontalAlignment="Left" VerticalAlignment="Top" HorizontalContentAlignment="Left" VerticalContentAlignment="Center"
FontFamily="Segoe UI" FontSize="16" FontWeight="Bold"
TextWrapping="NoWrap" IsReadOnlyCaretVisible="True" UndoLimit="10" AllowDrop="False" MaxLines="1"
MaxLength="20"
TextChanged="first_last_textbox_TextChanged"
PreviewTextInput="first_last_textbox_PreviewTextInput"
Text="{Binding First_Textbox, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}">
</TextBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
So, this is likely NOT the ideal way to do this, but it works. First we add a bound tag to the TextBox within the DataTemplate
ItemsSource="{Binding ListBox_Item_Collection}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBox Text="{Binding First_Textbox, UpdateSourceTrigger=PropertyChanged, Mode=OneWay}"
Tag="{Binding Index}">
</TextBox>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
For simplicity I bound that tag to the corresponding index in the ItemSource collection.
int index = Add_User_Binding.Count;
ListBox_Item_Collection.Add(new SomeDataType()
{
Index = index,
The_Textbox = "Stuff in TextBox",
});
The next step is to add a KeyDown event in the user control that comes before this one. In that event we will find the element with that tag and then use the Dispatcher to focus it.
private void Preview_TextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
string tag = "0";
IEnumerable<TextBox> elements = FindVisualChildren<TextBox>(this).Where(x => x.Tag != null && x.Tag.ToString() == tag);
foreach (TextBox element in elements)
{
FocusElement(element);
}
}
}
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;
}
}
}
}
private void FocusElement(IInputElement element)
{
if (element != null)
{
Dispatcher.BeginInvoke
(System.Windows.Threading.DispatcherPriority.ContextIdle,
new Action(delegate ()
{
Keyboard.Focus(element);
}));
}
}
As you can see, lots of work for something that should be much simpler.

Creating an Expand All and Collapse All Buttons with Expander in WPF

I am working in Visual Studio 2013 in WPF (C#) and I have the following code to create an expander from my xml. It is currently working perfectly right now but I want to include an expand all and collapse all buttons. I have looked all over and can't seem to find a solution.
Here is where the expander is created. I know I just have to iterate through a list of items and change the Property="IsExpanded" to Value="True" to create an expand all.
<DataTemplate x:Key="dtListTemplate" >
<StackPanel>
<Expander LostFocus="CollapseExpander" ExpandDirection="Down" Width="Auto">
<Expander.Style>
<Style TargetType="Expander">
<Setter Property="IsExpanded" Value="False" />
<Setter Property="Header" Value="{Binding XPath=#Name}" />
<Setter Property="FontWeight" Value="Bold"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsExpanded,RelativeSource={RelativeSource Self}}" Value="True">
</DataTrigger>
</Style.Triggers>
</Style>
</Expander.Style>
<ListBox Name="itemsList"
ItemsSource="{Binding XPath=UpgradeAction}"
ItemTemplate="{StaticResource dtListItemTemplate}"
SelectionChanged="listItems_SelectionChanged"
Style="{StaticResource styleListBoxUpgradeAction}"
ItemContainerStyle="{StaticResource styleListBoxItemUpgradeAction}">
</ListBox>
</Expander>
</StackPanel>
</DataTemplate>
Here's the code that calls the DataTemplate which has information from an Xml.
<StackPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right">
<Border Grid.Column="0" Grid.Row="0" Width="790" Height="40" Padding="5" Background="#4E87D4">
<Label VerticalAlignment="Center" FontSize="16" FontWeight="Bold" Foreground="White">Test</Label>
</Border>
<Button Name="ExpandBttn" Width="100" Height="40" FontSize="16" FontWeight="Bold" Content="Expand All" DataContext="{Binding}" Click="Expand_Button_Click"/>
<Button Name="ColapseBttn" Width="100" Height="40" FontSize="16" FontWeight="Bold" Content="Colapse All" DataContext="{Binding}" Click="Collapse_Button_Click"/>
</StackPanel>
<ListView Name="listItems" Grid.Column="0" Grid.Row="1" Background="Wheat"
ItemsSource="{Binding Source={StaticResource xmldpUpgradeActions}, XPath=ActionGroup}"
ItemTemplate="{StaticResource dtListTemplateRichards}"
SelectionChanged="listItems_SelectionChanged">
</ListView>
</StackPanel>
Here's what I tried in the .cs file for the expand all portion.
private void Expand_Button_Click(object sender, RoutedEventArgs e)
{
foreach(var item in listItems.Items)
{
var listBoxItem = listItems.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;
var itemExpander = (Expander)GetExpander(listBoxItem);
if (itemExpander != null)
itemExpander.IsExpanded = true;
}
}
private static DependencyObject GetExpander(DependencyObject container)
{
if (container is Expander) return container;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(container); i++)
{
var child = VisualTreeHelper.GetChild(container, i);
var result = GetExpander(child);
if (result != null)
{
return result;
}
}
return null;
}
Any help is greatly appreciated!
Is xmldpUpgradeActions a CollectionViewSource?
Whatever class is in the collection, it should implement INotifyPropertyChanged.
Give it an IsExpanded property that raises PropertyChanged in its setter when its value changes, and bind that to Expander.IsExpanded in the template:
<Expander
IsExpanded="{Binding IsExpanded}"
LostFocus="CollapseExpander"
ExpandDirection="Down"
Width="Auto">
Write a command that loops through all the items in the collection and sets item.IsExpanded = false; on each one.

WPF Datagrid Footer by Code Behind => Access Column by Binding

I want make a footer to my DataGrid using this method:
How do I add a footer row in a WPF datagrid?
But, i need to make this by code behind, and that's don't working.
I think it's because the binding of the grid can't find the column.
private DataGridColumn dgInsertCol(ref int idx, DataGridColumn dgc, tblEtatRecapColonne pCol, string pBinding = "") {
var dhHeadName = $"dgHead{pCol.Id}";
dgc.SetValue(NameProperty, dhHeadName);
dgc.HeaderTemplate = GetDtHeader(pCol, pBinding);
dgc.Width = new DataGridLength(1.0, (ckbSize.IsChecked.Value) ? DataGridLengthUnitType.Star : DataGridLengthUnitType.SizeToCells);
dgMain.Columns.Insert(idx++, dgc);
// Faire le footer associƩ
var t = new TextBlock() { Margin = new Thickness(5, 0, 0, 0), Text = pBinding, Background = new SolidColorBrush(Color.FromRgb(50, 100, 150)) };
var g = new Grid() { MinWidth = 10 };
g.SetBinding(Grid.WidthProperty, new Binding("ActualWidth") { ElementName = dhHeadName, Path=new PropertyPath("ActualWidth", null) }); // DataGridColumn
g.Children.Add(t);
pnlDgFooter.Children.Add(g);
return dgc;
}
<DataGrid Grid.Row="1" x:Name="dgMain" AutoGenerateColumns="False" SelectionUnit="FullRow" LoadingRow="dgMain_LoadingRow" MouseDown="dgMain_MouseDown" Sorting="dgMain_Sorting"
CanUserReorderColumns="False" CanUserResizeColumns="True" CanUserResizeRows="False" CanUserSortColumns="True" CanUserAddRows="False"
Style="{StaticResource dg}" RowStyle="{StaticResource dgRow}" CellStyle="{StaticResource dgCell}" ColumnHeaderStyle="{StaticResource dgColHeader}" RowHeaderStyle="{StaticResource dgRowHeader}"
ItemsSource="{Binding NotifyOnSourceUpdated=True, Source={StaticResource cvsElmts}}" HorizontalAlignment="Left">
<!--DataGrid.DataContext><Binding Source="{StaticResource tblUsers}"/></DataGrid.DataContext-->
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<mvvm:EventToCommand Command="{Binding SendCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=dgMain}" PassEventArgsToCommand="False"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,5"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" BorderThickness="1,1,1,5">
<Expander.Header>
<DockPanel>
<TextBlock FontWeight="Bold" Text="{Binding Path=Name}" Margin="5,0,0,0" Width="100"/>
<TextBlock FontWeight="Bold" Text="{Binding Path=ItemCount}"/>
</DockPanel>
</Expander.Header>
<Expander.Content>
<ItemsPresenter />
</Expander.Content>
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
<!-- Style for groups under the top level. -->
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<DockPanel Background="LightBlue">
<TextBlock Text="{Binding Path=Name}" Foreground="Blue" Margin="30,0,0,0" Width="100"/>
<TextBlock Text="{Binding Path=ItemCount}" Foreground="Blue"/>
</DockPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</DataGrid.GroupStyle>
<DataGrid.Columns>
<StaticResource ResourceKey="rowBtnDetail"/>
</DataGrid.Columns>
</DataGrid>
<StackPanel Grid.Row="2" Name="pnlDgFooter" HorizontalAlignment="Left" Orientation="Horizontal" >
</StackPanel>
Why use ElementName at all? Set the Source of the Binding directly. Also, don't set Path twice, so either write
g.SetBinding(Grid.WidthProperty,
new Binding
{
Source = dgc,
Path = new PropertyPath("ActualWidth")
});
or
g.SetBinding(Grid.WidthProperty, new Binding("ActualWidth") { Source = dgc });

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.

Checkbox ListView WPF C#

I will start developing for WPF and I have a doubt.
I created a ListView with the Binding property to the next ExtComandaDTO the object. The property in "seleciona" has relationship with a checkbox, but I have following problem.
When I click the checkbox it calls the normal event, but when I change the value of "seleciona" at runtime checkbox in my listview is selected but does not call the event check.
There is missing from Listview to be called the event some attribute?
<ListView x:Name="LvwComanda" Grid.Column="0"
Background="{x:Null}"
Margin="40,36,40,40"
SelectedItem="{Binding SelectedExtComanda}"
ItemsSource="{Binding ObsExtComanda, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.RowSpan="2" >
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Finaliza Comanda" Checked="LvwComandaRowFinalizaComanda_Click" Unchecked="LvwComandaRowFinalizaComanda_Click"></MenuItem>
</ContextMenu>
</ListView.ContextMenu>
<ListView.Resources>
<Style TargetType="{x:Type ListViewItem}">
<Style.Triggers>
<DataTrigger Binding="{Binding finaliza_pendente}" Value="true">
<Setter Property="Foreground" Value="Red" />
</DataTrigger>
<DataTrigger Binding="{Binding finalizada}" Value="true">
<Setter Property="Foreground" Value="DarkViolet" />
</DataTrigger>
</Style.Triggers>
</Style>
</ListView.Resources>
<ListView.View>
<GridView >
<GridViewColumn Width="30">
<GridViewColumn.CellTemplate>
<DataTemplate >
<CheckBox Name="ChkComanda" IsChecked="{Binding seleciona.IsChecked, Mode=TwoWay}" Checked="Checked_LvwComandaRow" Unchecked="Unchecked_LvwComandaRow" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn Width="Auto" Header="Comanda" DisplayMemberBinding="{Binding nr_comanda}"/>
<GridViewColumn Width="Auto" Header="Taxa Servico" DisplayMemberBinding="{Binding taxa_servico}" />
<GridViewColumn Width="Auto" Header="Finalizada" DisplayMemberBinding="{Binding finalizada, Converter={StaticResource ReplaceConvertSimNao}}" />
<GridViewColumn Width="Auto" Header="Observacao" DisplayMemberBinding="{Binding observacao}"/>
</GridView>
</ListView.View>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Margin" Value="0,0,0,0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander IsExpanded="True" BorderBrush="#FFA4B97F" BorderThickness="0,0,0,1">
<Expander.Header>
<DockPanel>
<DockPanel.ContextMenu>
<ContextMenu Loaded="LvwComandaHeaderContextMenu_Loaded">
<MenuItem Header="Libera Mesa" Checked="LvwComandaHeaderLiberaMesa_Click" Unchecked="LvwComandaHeaderLiberaMesa_Click" />
</ContextMenu>
</DockPanel.ContextMenu>
<CheckBox x:Name="HeaderCheckBox" Checked="Checked_LvwComandaHeader" Unchecked="Unchecked_LvwComandaHeader">
<StackPanel Orientation="Horizontal">
<TextBlock FontWeight="Bold" Text="{Binding Name, Converter={StaticResource ReplaceConvertMesaId}}" Margin="5,0,0,0"/>
<TextBlock Width="Auto" Text=" " />
<TextBlock FontWeight="Bold" Width="Auto" Text="{Binding Name, Converter={StaticResource ReplaceConvertMesaGrupo}}" />
<TextBlock Text=" ("/>
<TextBlock Text="{Binding ItemCount, Converter={StaticResource ReplaceConvertComanda}}"/>
<TextBlock Text=")"/>
</StackPanel>
</CheckBox>
</DockPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</ListView.GroupStyle>
</ListView>
#region Event List Row Comanda
private void Checked_LvwComandaRow(object sender, RoutedEventArgs e)
{
this.Handle_LvwComandaRow((CheckBox)sender, true);
}
private void Unchecked_LvwComandaRow(object sender, RoutedEventArgs e)
{
this.Handle_LvwComandaRow((CheckBox)sender, false);
}
private void Handle_LvwComandaRow(CheckBox sender, bool check)
{
if (sender.DataContext is ExtComandaDTO)
{
var row = (ExtComandaDTO)sender.DataContext;
if (check)
{
ObsExtComanda.FindAll(c => c.seleciona && c.id_mesa != row.id_mesa).ForEach(c => c.seleciona = false);
}
bool bolComandaSelected = ObsExtComanda.Exists(c => c.seleciona);
BtPagamento.IsEnabled = bolComandaSelected;
BtImprimir.IsEnabled = bolComandaSelected;
this.PrepareObsPedido(check, row);
this.PrepareObsComandaPagto(check, row);
}
}
public class ExtComandaDTO : ComandaDTO, INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(String property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
private Boolean _seleciona;
private Boolean _finaliza_pendente;
public Boolean seleciona
{
get { return _seleciona; }
set { _seleciona = value; OnPropertyChanged("seleciona"); }
}
public new Boolean finaliza_pendente
{
get { return _finaliza_pendente; }
set { _finaliza_pendente = value; OnPropertyChanged("finaliza_pendente"); }
}
}
Checked and Unchecked are events fired by the UI (not a set).
Handle that stuff in the set if you want to catch changes from code.

Categories