SelectedItems from nested listview - c#

I am developing a Windows Store App in which I have a nested listview i.e. expandable listview. To retain the selected items in child listview I have used
<ListView Name="FiltersListview" ItemContainerStyle="{StaticResource StretchItemStyle}" SelectionChanged="FiltersListview_SelectionChanged" IsItemClickEnabled="True" ItemClick="FiltersListview_ItemClick" Grid.Row="1" Grid.ColumnSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="True">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Collapsed"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Visible"/>
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="False">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Visible"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Collapsed"/>
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<Grid Height="50" x:Name="view1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-down.png"/>
<Rectangle Fill="Black" VerticalAlignment="Bottom" Height="1" Grid.ColumnSpan="2"/>
</Grid>
<Grid x:Name="view2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-up.png"/>
<ListView Margin="20,0" Grid.Row="1" RequestedTheme="Light" Grid.ColumnSpan="2" ItemsSource="{Binding SubList}" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="FontSize" Value="22"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Foreground" Value="Black"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
and in code behind
private void FiltersListview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
var item = (sender as ListView).SelectedItem as FilterM;
if (item != null)
item.IsSelected = true;
if (e.RemovedItems.Count > 0)
{
foreach (var Nitem in e.RemovedItems)
{
(Nitem as FilterM).IsSelected = false;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private void FiltersListview_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
if ((sender as ListView).SelectedItem != null)
{
if ((sender as ListView).SelectedItem.Equals(e.ClickedItem))
(sender as ListView).SelectedItem = null;
else
(sender as ListView).SelectedItem = e.ClickedItem;
}
else
(sender as ListView).SelectedItem = e.ClickedItem;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
I have changed this question after my old question about it from here.
But now on tap of a button named Go I want to know all the selected items in child listviews of each item. I have stumbled upon links like this but I'm not using MVVM and unable to make it work in my case.
Can anybody help?

Well I have come up with a work around for this problem. I'm putting my solution if anybody needs it.
I have passed the child listview as parameter to ViewModel and managed it with help of command.
<ListView ItemContainerStyle="{StaticResource StretchItemStyle}" SelectionChanged="FiltersListview_SelectionChanged" IsItemClickEnabled="True" ItemClick="FiltersListview_ItemClick" Grid.Row="1" Grid.ColumnSpan="2" Margin="-1,0,1,44" Grid.RowSpan="2">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="True">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Collapsed"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Visible"/>
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="False">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Visible"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Collapsed"/>
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
<Grid Height="50" x:Name="view1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-down.png"/>
<Rectangle Fill="Black" VerticalAlignment="Bottom" Height="1" Grid.ColumnSpan="2"/>
</Grid>
<Grid x:Name="view2">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-up.png"/>
<ListView x:Name="SubListview" Margin="20,0" Grid.Row="1" RequestedTheme="Light" Grid.ColumnSpan="2" ItemsSource="{Binding SubList}" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="FontSize" Value="22"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Foreground" Value="Black"/>
</Style>
</ListView.ItemContainerStyle>
<Interactivity:Interaction.Behaviors>
<Core:EventTriggerBehavior EventName="SelectionChanged">
<Core:InvokeCommandAction Command="{Binding SelectionChangedCommand}" CommandParameter="{Binding ElementName=SubListview}"/>
<!--<Core:InvokeCommandAction Command="{Binding SelectionChangedCommand}" InputConverter="{StaticResource SelectionChangedConverter}" InputConverterParameter="{Binding ElementName=SubListview}"/>-->
</Core:EventTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</ListView>
<Rectangle Grid.Row="1" Fill="Black" VerticalAlignment="Bottom" Height="1" Grid.ColumnSpan="2"/>
</Grid>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
and in code behind
public class FilterM
{
public RelayCommand<IList<object>> SelectionChangedCommand
{
get
{
if (selectionChangedCommand == null)
{
selectionChangedCommand = new RelayCommand<IList<object>>(
items =>
{
// do something with selected items!
}
);
}
return selectionChangedCommand;
}
}
}
and set itemssource of First listview. I got this idea from this link. Hope it helps somebody like me.

Related

LiveCharts ColumnSeries not showing

I'm using LiveCharts in WPF to visualize the results of some analyses. The results of an analysis is added to a SeriesCollection and displayed in an CartesianChart. You can choose which type of series to use: LineSeries or ColumnSeries. The chosen type is then created and added to the SeriesCollection.
There's a custom mapper for selecting X and Y values from the ChartValues and a AxisFormatter for the X axis.
The charts are part of an Blacklight.Controls.Wpf.DragDockPanelHost. Each chart is an DragDockPanel with a style attached to it. The chart itself is a ContentControl with an TemplateSelector that returns the CartesianChart-XAML as a DataTemplate.
I've already tried to set the Fill or Stroke of the series or putting some ColumnSeries in there manually but that didn't help at all.
Filling of the SeriesCollection:
private SeriesCollection _Series;
public SeriesCollection Series
{
get { return _Series; }
set { SetProperty<SeriesCollection>(ref _Series, value); }
}
...
private void createDiagram()
{
if (this._Analysis!= null && this._Diagram != null)
{
this.Series.Clear();
foreach (KeyValuePair<state, Dictionary<DateTime, int>> kvp in this.Analysis.Execute())
{
Series series = Activator.CreateInstance(Diagram) as Series;
if (series != null)
{
series.Title = kvp.Key.name;
series.Values = new ChartValues<KeyValuePair<DateTime, int>>(kvp.Value);
this.Serien.Add(series);
}
}
}
}
Mapper and AxisFormatter:
CartesianMapper<KeyValuePair<DateTime, int>> mapper = Mappers.Xy<KeyValuePair<DateTime, int>>().X(kvp => ((DateTimeOffset)kvp.Key).ToUnixTimeSeconds()).Y(kvp => kvp.Value);
this.Series = new SeriesCollection(mapper);
this.XFormatter = value =>
{
return DateTimeOffset.FromUnixTimeSeconds((long)value).DateTime.ToString("dd.MM.yyyy HH:mm");
};
TemplateSelector:
public class DashboardElementTemplateSelector : DataTemplateSelector
{
public DataTemplate ListDashboardElementTemplate { get; set; }
public DataTemplate SingleValueDashboardElementTemplate { get; set; }
public override DataTemplate SelectTemplate(object item, DependencyObject container)
{
if (item is ListDashboardElementViewModel)
return this.ListDashboardElementTemplate;
else
return this.SingleValueDashboardElementTemplate;
}
}
XAML of DragDockPanelHost:
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<DataTemplate x:Key="listElement">
<views:ListDashboardElementView/>
</DataTemplate>
<DataTemplate x:Key="singleValueElement">
<views:SingleValueDashboardElementView/>
</DataTemplate>
<tempselect:DashboardElementTemplateSelector x:Key="elementTempSelector"
ListDashboardElementTemplate="{StaticResource listElement}"
SingleValueDashboardElementTemplate="{StaticResource singleValueElement}"
/>
</ResourceDictionary>
<ResourceDictionary>
<conv:BooleanToVisibilityConverter x:Key="visCon"/>
</ResourceDictionary>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</UserControl.Resources>
<bl:DragDockPanelHost ItemsSource="{Binding Diagrams}" Grid.Row="1" Margin="20" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<bl:DragDockPanelHost.Style>
<Style TargetType="bl:DragDockPanelHost">
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<Canvas ClipToBounds="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
</Canvas>
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="bl:DragDockPanelHost">
<ItemsPresenter/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</bl:DragDockPanelHost.Style>
<bl:DragDockPanelHost.DefaultPanelStyle>
<Style TargetType="{x:Type bl:DragDockPanel}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Margin="10">
<Grid Margin="5">
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Border Background="#00000000" Margin="-2" Padding="5" Grid.Row="0">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<WrapPanel>
<Image Width="20" x:Name="GripBarElement" Source="/Aisys.XStorage.Dashboard;component/Images/move.png" Grid.Column="0" Cursor="Hand" HorizontalAlignment="Left"/>
<TextBlock Text="{Binding Name}" Grid.Column="0" FontSize="16" FontWeight="Bold" Margin="10,0,0,0"/>
</WrapPanel>
<WrapPanel HorizontalAlignment="Right" Grid.Column="2">
<Button Command="{Binding ExecuteCommand}" CommandParameter="{Binding}" Margin="5,0,5,0">
<Button.Template>
<ControlTemplate>
<Image Source="/Aisys.XStorage.Dashboard;component/Images/Refresh.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Width="20" Command="{Binding DataContext.RemoveDiagramCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type bl:DragDockPanelHost}}}" CommandParameter="{Binding}">
<Button.Template>
<ControlTemplate>
<Image Source="/Aisys.XStorage.Dashboard;component/Images/Remove.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<Button Command="{Binding DataContext.ShowPropertiesCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type bl:DragDockPanelHost}}}" CommandParameter="{Binding}" Margin="5,0,5,0">
<Button.Template>
<ControlTemplate>
<Image Source="/Aisys.XStorage.Dashboard;component/Images/Preferences.png"/>
</ControlTemplate>
</Button.Template>
</Button>
<ToggleButton x:Name="MaximizeToggleButton" VerticalAlignment="Top" HorizontalAlignment="Right" IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay, Path=IsMaximized}" Margin="0,5,5,0" Width="25" Height="25" Cursor="Hand">
<ToggleButton.Template>
<ControlTemplate TargetType="ToggleButton">
<Image Source="/Aisys.XStorage.Dashboard;component/Images/Maximize.png" Margin="0,0,0,5"/>
</ControlTemplate>
</ToggleButton.Template>
</ToggleButton>
</WrapPanel>
</Grid>
</Border>
<Separator VerticalAlignment="Bottom" Margin="0,0,0,0"/>
<ContentControl Content="{Binding}" ContentTemplateSelector="{StaticResource elementTempSelector}" Grid.Row="1" Margin="10"/>
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</bl:DragDockPanelHost.DefaultPanelStyle>
</bl:DragDockPanelHost>
XAML of chart:
<Grid>
<lvc:CartesianChart Series="{Binding Series}" LegendLocation="Right" Name="chart">
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="Zeit" LabelFormatter="{Binding XFormatter}">
</lvc:Axis>
</lvc:CartesianChart.AxisX>
</lvc:CartesianChart>
</Grid>
If I'm choosing LineSeries, everything works fine. But when I'm using ColumnSeries nothing is shown. You can see, that the axis is redrawn and the separators move. The legend is also drawn, but there are no columns visible.
Any ideas why this is happening?
I had the same problem recently. Unfortunately, this doesn't seem to be documented anywhere but for some reason if you have too many data points for the size of the graph, then none of the columns will display. You can either try reducing the number of data points until it works (in my case 90 data points wouldn't display, but 30 would), or on ColumnSeries there is a property ColumnPadding that you can turn down to zero and see if that helps.

Assign Each TreeViewItem to Its Own Grid Row

The latest in my endeavors - I've managed to populate a treeview with elements, and populate a listbox next to it with related elements.
The trick is that, I'm trying to think of a way to assign each listbox item and corresponding treeview item it's own grid row, that would be generated probably in back C# code to with corresponding row definitions based on the control's number of children, if that makes any sense.
I've tried looking at the post below to see if I can select each treeview item this way, but to no avail:
How to programmatically select an item in a WPF TreeView?
Here's some example code that tries to implement this - I keep getting null values, though, and using UpdateLayout() before the loop on the controls doesn't seem to help. :/
for (int i = 0; i < loadedAR.Item2.Count; i++)
{
DABsAndIssuesGrid.RowDefinitions.Add(new RowDefinition());
var selectedItemObjectDAB = DABView.Items.GetItemAt(i);
var DABParent = DABView.Parent;
TreeViewItem currentItemDAB = DABView.ItemContainerGenerator.ContainerFromItem(selectedItemObjectDAB)
as TreeViewItem;
if (currentItemDAB != null)
Grid.SetRow(currentItemDAB, i);
var selectedItemObjectErr = IssueBox.Items.GetItemAt(i);
TreeViewItem currentItemErr = DABView.ItemContainerGenerator.ContainerFromItem(selectedItemObjectErr)
as TreeViewItem;
if (currentItemErr != null)
Grid.SetRow(currentItemErr, i);
}
Is there a better way to do this than the way I'm trying to do it? I've tried using a converter to assign the row dynamically too as they would get generated, but that still appears to put all of my children in the same first grid row...
Here's my XAML:
<Window x:Class="Client_Invoice_Auditor.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Client_Invoice_Auditor"
xmlns:self="clr-namespace:Client_Invoice_Auditor.CoreClient"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="1000">
<Window.Resources>
<self:SelfPayConverter x:Key="FINConverter"/>
<self:ErrorExpandConverter x:Key="ErrorExpandConverter"/>
<self:AssignRowConverter x:Key="AssignRowConverter"/>
</Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="20*"/>
<RowDefinition Height="80*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0">
<StackPanel Orientation="Vertical">
<DockPanel VerticalAlignment="Top" Height="20" Panel.ZIndex="1">
<Menu Name="fileMenu" Width="Auto" DockPanel.Dock="Top">
<MenuItem Header="File">
<MenuItem Header="Open Account File" Click="menuOpenFile_Click"/>
<MenuItem Header="Exit" Click="menuExit_Click"/>
</MenuItem>
<MenuItem Header="Options">
<!--<MenuItem Header="Update" Click="update_Click"/>-->
<MenuItem Header="About" Click="about_Click"/>
</MenuItem>
</Menu>
</DockPanel>
<WrapPanel Orientation="Horizontal" HorizontalAlignment="Center" Height="Auto">
<StackPanel Width="Auto" Orientation="Horizontal" HorizontalAlignment="Center">
<Border BorderBrush="MediumAquamarine" BorderThickness="2">
<Label Name="AccountNumber"/>
</Border>
<Border BorderBrush="MediumAquamarine" BorderThickness="2">
<Label Name="AcctDesc"/>
</Border>
<Border BorderBrush="MediumAquamarine" BorderThickness="2">
<Label Name="Organization"/>
</Border>
</StackPanel>
</WrapPanel>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<Label Margin="20,10,0,0" Content="Activity Date Time" />
<Label Margin="60,10,0,0" Content="Beginning Balance" />
<Label Margin="10,10,0,0" Content="Charge Amount" />
<Label Margin="30,10,0,0" Content="Adjustments" />
<Label Margin="40,10,0,0" Content="Payments" />
<Label Margin="60,10,0,0" Content="End Balance" />
<Label Margin="50,10,0,0" Content="Issues" />
</StackPanel>
</StackPanel>
</Grid>
<Grid Grid.Row="1" Grid.Column="0">
<Grid Name="DABsAndIssuesGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80*"/>
<ColumnDefinition Width="20*"/>
</Grid.ColumnDefinitions>
<TreeView Name="DABView" Grid.Column="0">
<!--<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding FinClass, Converter={StaticResource ErrorExpandConverter}}" />
</Style>-->
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded"
Value="{Binding Dummies, Converter={StaticResource ErrorExpandConverter}}" />
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type self:dailyAccountBalance}" ItemsSource="{Binding Dummies}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left" IsEnabled="False">
<TextBlock Width="150" Text="{Binding DabActivityDate}" />
<TextBlock Width="100" Margin="20,0,0,0" Text="{Binding BegBalance}"/>
<TextBlock Width="100" Margin="20,0,0,0" Text="{Binding ChrgAmount}" />
<TextBlock Width="100" Margin="20,0,0,0" Text="{Binding AdjAmount}" />
<TextBlock Width="100" Margin="20,0,0,0" Text="{Binding PmtAmount}" />
<TextBlock Width="100" Margin="20,0,0,0" Text="{Binding EndBalance}" />
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate DataType="{x:Type self:DummyItem}">
<StackPanel Orientation="Horizontal" HorizontalAlignment="Left">
<!--<TextBlock Text="{Binding Text}" />-->
<DataGrid ItemsSource="{Binding ChargeActivities}" AutoGenerateColumns="False">
<DataGrid.Style>
<Style TargetType="{x:Type DataGrid}">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Items.Count,
RelativeSource={RelativeSource Self}}" Value="0">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGrid.Style>
<DataGrid.Columns>
<DataGridTextColumn x:Name="ChrgID" Header=" Charge" Binding="{Binding ChargeID}" />
<DataGridTextColumn x:Name="ChrgType" Header="Charge Type" Binding="{Binding ChargeType}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<Trigger Property="Text" Value="CR">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="ChrgAmt" Header="Amount" Binding="{Binding ChargeAmount}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger Binding="{Binding ChargeType}" Value="CR">
<Setter Property="Foreground" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
<DataGridTextColumn x:Name="FIN" Header="FIN" Binding="{Binding EncntrAlias}" />
<DataGridTextColumn x:Name="FINClass" Header="FIN Class" Binding="{Binding FinClass}">
<DataGridTextColumn.ElementStyle>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground" Value="{Binding FinClass, Converter={StaticResource FINConverter}}"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
<!--<TreeViewItem x:Key="Test">
<TextBlock Text="Me gusta"></TextBlock>
</TreeViewItem>-->
</TreeView.ItemTemplate>
</TreeView>
<Border Grid.Column="1" BorderBrush="Black" BorderThickness="2">
<ListBox Name="IssueBox" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="Hi"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
</Grid>
</Grid>
</Grid>
</Window>
And, here's the code behind:
using Client_Invoice_Auditor.CoreClientAR;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Client_Invoice_Auditor
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public string accountFile;
public MainWindow()
{
InitializeComponent();
OpenaccountFile();
}
private void OpenaccountFile()
{
accountFile = "";
//errorFilters.Clear();
// Displays an OpenFileDialog so the user can select a file.
Microsoft.Win32.OpenFileDialog openFileDialog1 = new Microsoft.Win32.OpenFileDialog();
openFileDialog1.Filter = "Account Files|*.acct";
openFileDialog1.Title = "Select an account File";
if (openFileDialog1.ShowDialog() == true)
{
// Assign the cursor in the Stream to the Form's Cursor property.
accountFile = openFileDialog1.FileName;
//claimFile = openFileDialog1.OpenFile().ToString();
//openFileDialog1.Dispose();
}
if (accountFile == "")
{
/*System.Windows.MessageBox.Show("File must be selected in order to continue - exiting now."
, "No File Selected", MessageBoxButton.OK);
this.Close();*/
if (!AcctDesc.HasContent)
{
AcctDesc.Content = "No Account File Loaded";
//Version version = Assembly.GetExecutingAssembly().GetName().Version;
//manualBreakItem.IsEnabled = false;
//manualValidateItem.IsEnabled = false;
}
}
else
{
//openFileDialog1 = null;
Console.WriteLine("Account file path is: " + accountFile);
//claimFile = "C:\\Users\\KO054202\\Documents\\pft_1450_out\\pft_1450_out\\CAR837I125114220170601.out";
DataTable dataAR = new DataTable();
try
{
Tuple<accountARHeader, List<dailyAccountBalance>, DataTable> loadedAR = dabARLoader.LoadARData(accountFile);
//dataAR = loadedAR.Item2;
AccountNumber.Content = "Account Number: " + loadedAR.Item1.AccountNumber;
AcctDesc.Content = "Description: " + loadedAR.Item1.AccountDescription;
Organization.Content = "Client Organization: " + loadedAR.Item1.OrganizationName;
//TreeViewItem dummy = new TreeViewItem();
//dummy.DataContext = "Hi";
//DummyItem testThis = new DummyItem("Test2");
//testThis.Text = "Hi";
//loadedAR.Item2.First().Dummies.Add(testThis);
DABView.ItemsSource = loadedAR.Item2;
IssueBox.ItemsSource = dabARLoader.loadIssues(loadedAR.Item2);
DABView.UpdateLayout();
for (int i = 0; i < loadedAR.Item2.Count; i++)
{
DABsAndIssuesGrid.RowDefinitions.Add(new RowDefinition());
var selectedItemObjectDAB = DABView.Items.GetItemAt(i);
var DABParent = DABView.Parent;
TreeViewItem currentItemDAB = DABView.ItemContainerGenerator.ContainerFromItem(selectedItemObjectDAB)
as TreeViewItem;
if (currentItemDAB != null)
Grid.SetRow(currentItemDAB, i);
var selectedItemObjectErr = IssueBox.Items.GetItemAt(i);
TreeViewItem currentItemErr = DABView.ItemContainerGenerator.ContainerFromItem(selectedItemObjectErr)
as TreeViewItem;
if (currentItemErr != null)
Grid.SetRow(currentItemErr, i);
}
//DABView.DisplayMemberPath = "A";
}
catch (Exception e)
{
System.Windows.MessageBox.Show("I don't wanna open this file! Try another. Error: " + e.Message);
OpenaccountFile();
}
}
}
private void menuOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenaccountFile();
}
private void menuExit_Click(object sender, RoutedEventArgs e)
{
Close();
}
private void about_Click(object sender, RoutedEventArgs e)
{
System.Windows.MessageBox.Show("I heard you like clicking buttons.");
}
}
}
I have a TreeView inside of a Grid, along with a ListBox control. The
idea is that the TreeView would populate parent items by a daily
account balance, and then for each one of those an adjacent list of
issues would be displayed in the neighboring ListBox
I would make specialized Data Transfer Object (DTO)s where each instance item generates the values for the properties to be shown and where required creates child DTOs for that instance. Then those DTOs are bindable between all the controls. Meaning that you have this class defined
<Top Level Class used by the grid<DTO>>
<Properties et all>
<List of Items in for treeview>
<Treeview class <DTO>>
<Properties et all>
<List of Items in for listbox>
<Listbox class <DTO>>
<Properties et all>
Then bind the grid to the above top level DTO list.
Bind the treeview to the current row's treeview list items.
Bind the listbox to the current treeview's selected item's Listbox items list.
Once the DTOs are created then it simply becomes an exercise in binding.

FlowDocument from XAML is not Responsive when Printing

The problem is that when I print the FlowDocument, it prints the same as what the Window is showing, and not the FlowDocument itself.
Here's the XAML:
<Window x:Class="POS.DailySalesReport"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:POS"
mc:Ignorable="d"
Height="500"
Width="816"
Loaded="Window_Loaded"
WindowStartupLocation="CenterScreen">
<Grid>
<FlowDocumentPageViewer x:Name="flwView">
<FlowDocument x:Name="flwDoc"
TextAlignment="Center"
ColumnWidth="{Binding ElementName=flwView, Path=ActualWidth}">
<BlockUIContainer>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid x:Name="grdDetails"
Grid.Row="0"
Grid.Column="0"
Margin="0,0,0,30">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Ellipse Grid.Row="0"
Grid.Column="0"
Height="90"
Width="90"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<Ellipse.Fill>
<ImageBrush x:Name="imgUser" />
</Ellipse.Fill>
</Ellipse>
<Grid Grid.Row="0"
Grid.Column="1"
Margin="10, 0, 0, 0">
<Grid.RowDefinitions>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock x:Name="lblCompanyName"
Grid.Row="0"
Grid.Column="0"
Text="COMPANY NAME"
FontFamily="{StaticResource RobotoRegular}"
FontSize="18"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
<TextBlock x:Name="lblCompanyAddress"
Grid.Row="1"
Grid.Column="0"
Text="Business Address"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
<TextBlock x:Name="lblCompanyNumber"
Grid.Row="2"
Grid.Column="0"
Text="Contact Number"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
<TextBlock x:Name="lblCompanyTIN"
Grid.Row="3"
Grid.Column="0"
Text="TIN Number"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
VerticalAlignment="Center"
HorizontalAlignment="Left" />
</Grid>
<StackPanel Grid.Row="0"
Grid.Column="2">
<TextBlock x:Name="lblReportType"
FontFamily="{StaticResource RobotoBold}"
FontSize="12"
HorizontalAlignment="Right" />
<TextBlock x:Name="lblReportDate"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
HorizontalAlignment="Right" />
</StackPanel>
</Grid>
<ListView x:Name="lstView"
Grid.Row="1"
Grid.Column="0"
BorderThickness="0"
SelectionMode="Single"
Width="{Binding ElementName=flwDoc, Path=ActualWidth}">
<ListView.Resources>
<Style TargetType="{x:Type GridViewColumnHeader}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="White" />
</Setter.Value>
</Setter>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Black" />
</Setter.Value>
</Setter>
<Setter Property="FontSize"
Value="11" />
<Setter Property="FontFamily"
Value="{StaticResource RobotoMedium}" />
<Setter Property="Height"
Value="35" />
<Setter Property="BorderThickness"
Value="0, 1, 0, 1" />
<Setter Property="BorderBrush">
<Setter.Value>
<SolidColorBrush Color="Black" />
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListView}">
<Setter Property="Background">
<Setter.Value>
<SolidColorBrush Color="White" />
</Setter.Value>
</Setter>
</Style>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="HorizontalContentAlignment"
Value="Stretch" />
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Black"
Opacity="0.8" />
</Setter.Value>
</Setter>
<Setter Property="FontFamily"
Value="{StaticResource RobotoMedium}" />
<Setter Property="FontSize"
Value="17" />
<Setter Property="Background"
Value="White" />
<Setter Property="Padding"
Value="0, 10, 0, 10" />
<Setter Property="Margin"
Value="0, 0, 0, 10" />
<Style.Resources>
<!-- Foreground for Selected ListViewItem -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}"
Color="Black"
Opacity="0.8" />
<!-- Background for Selected ListViewItem -->
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="White" />
<!-- Foreground for Inactive Selected ListViewItem -->
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}"
Color="Black"
Opacity="0.8" />
<!-- Background for Inactive Selected ListViewItem -->
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="White" />
</Style.Resources>
</Style>
</ListView.Resources>
<ListView.View>
<GridView>
<GridViewColumn x:Name="lstHeader1"
Header="Description">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductDescription}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="lstHeader2"
Header="Supplier">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding Supplier}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="lstHeader3"
Header="Sold">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductSold}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="lstHeader4"
Header="Cost Price">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductCost}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="lstHeader5"
Header="Retail Price">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding ProductRetail}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn x:Name="lstHeader6"
Header="Total(Qty * Retail Price)">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding TotalRetail}"
TextAlignment="Center"
FontFamily="{StaticResource RobotoRegular}"
FontSize="12"
TextWrapping="Wrap" />
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
<Grid Grid.Row="2"
Grid.Column="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid Grid.Row="0"
Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0"
Grid.Column="0"
Text="Total Items Sold"
HorizontalAlignment="Right"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoBold}" />
<TextBlock x:Name="lblTotalSold"
Grid.Row="0"
Grid.Column="1"
Text="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoRegular}" />
<TextBlock Grid.Row="1"
Grid.Column="0"
Text="Total Cost Amount"
HorizontalAlignment="Right"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoBold}" />
<TextBlock x:Name="lblTotalCost"
Grid.Row="1"
Grid.Column="1"
Text="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoRegular}" />
<TextBlock Grid.Row="2"
Grid.Column="0"
Text="Total Retail Amount"
HorizontalAlignment="Right"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoBold}" />
<TextBlock x:Name="lblTotalRetail"
Grid.Row="2"
Grid.Column="1"
Text="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoRegular}" />
<TextBlock Grid.Row="3"
Grid.Column="0"
Text="Profit"
HorizontalAlignment="Right"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoBold}" />
<TextBlock x:Name="lblProfit"
Grid.Row="3"
Grid.Column="1"
Text="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontSize="10"
FontFamily="{StaticResource RobotoRegular}" />
</Grid>
</Grid>
</Grid>
</BlockUIContainer>
</FlowDocument>
</FlowDocumentPageViewer>
</Grid>
</Window>
Overall, the items in the ListView is dynamic. The problem appears when the list became longer than the height of the Window, ruining the appearance of the report (like the ellipse), and it is the same as the printed version.
Here's the code-behind:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
PrintDialog printDlg = new PrintDialog();
var actualWidth = lstView.ActualWidth - 10;
lstHeader1.Width = actualWidth / 6;
lstHeader2.Width = actualWidth / 6;
lstHeader3.Width = actualWidth / 6;
lstHeader4.Width = actualWidth / 6;
lstHeader5.Width = actualWidth / 6;
lstHeader6.Width = actualWidth / 6;
PopulateListView(ChosenDate);
string businessName = "";
string businessAddress = "";
string businessTIN = "";
string businessContact = "";
string businessImage = "";
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
string query = "SELECT * FROM dbo.Company";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
try
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
businessName = reader["Name"].ToString();
businessAddress = reader["Address"].ToString();
businessTIN = reader["TIN"].ToString();
businessContact = reader["Contact"].ToString();
businessImage = reader["ImagePath"].ToString();
}
}
}
}
catch (Exception err)
{
MessageBox.Show(err.Message + err.StackTrace);
}
}
}
BitmapImage img;
if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + businessImage))
{
img = new BitmapImage();
img.BeginInit();
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = new Uri(AppDomain.CurrentDomain.BaseDirectory + businessImage);
img.EndInit();
}
else
{
img = new BitmapImage(new Uri("pack://application:,,,/Resources/default_product_img.png"));
}
imgUser.ImageSource = img;
lblCompanyName.Text = businessName;
lblCompanyAddress.Text = businessAddress;
lblCompanyTIN.Text = businessTIN;
lblCompanyNumber.Text = businessContact;
lblReportType.Text = ReportType;
lblReportDate.Text = ChosenDate.ToString("MM/dd/yyyy");
lblTotalSold.Text = TotalSold.ToString();
lblTotalCost.Text = TotalCost.ToString("F2");
lblTotalRetail.Text = TotalRetail.ToString("F2");
lblProfit.Text = TotalProfit.ToString("F2");
IDocumentPaginatorSource idpSource = flwDoc;
var result = printDlg.ShowDialog();
if (result == true)
{
printDlg.PrintDocument(idpSource.DocumentPaginator, "Document");
}
}
I thought that the UI appearing in the Window is just for visual display, and not really what the PrintDialog prints, but the FlowDocument itself. If it is not possible, I'm planning to re-create the controls in code-behind just to maintain responsiveness. So I'm asking here first if there is a fix for this.

Scrolling to active tabcontrol header in stackpanel in WPF

With the following code I can create a non wrapped scrolling stackpanel of headers of a tabcontrol. It has repeat buttons that can control the scroll. I would like instead for the repeat buttons to be able to control which tab is active, and adjust the scroll so the active tab can scroll into view. Is such a thing possible?
<TabControl SelectedItem="{Binding ActiveTicketFilterTab, Mode=TwoWay}"
Margin="5"
Grid.Row="1"
BorderBrush="Gray"
BorderThickness="2"
Style="{StaticResource ResourceKey=somestyle}"
SelectionChanged="selectionchanged"
Name="somename"
Background="#252525"
ItemsSource="{Binding someobslist}"
Grid.ColumnSpan="2">
<TabControl.Resources>
<Style x:Key="TabScrollerRepeatButtonStyle" TargetType="{x:Type RepeatButton}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Border Background="sc#1, 0.366693377, 0.372125238, 0.6931424">
<ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" Content="{TemplateBinding ContentControl.Content}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.Resources>
<TabControl.Template>
<ControlTemplate TargetType="{x:Type TabControl}">
<Grid ClipToBounds="true" SnapsToDevicePixels="true" KeyboardNavigation.TabNavigation="Local">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="ColumnDefinition0"/>
<ColumnDefinition x:Name="ColumnDefinition1" Width="0"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition x:Name="RowDefinition0" Height="Auto"/>
<RowDefinition x:Name="RowDefinition1" Height="*"/>
</Grid.RowDefinitions>
<ScrollViewer Panel.ZIndex="1" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Disabled">
<ScrollViewer.Style>
<Style TargetType="{x:Type ScrollViewer}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate>
<Grid Margin="0,0,0,0" Grid.Row="0" Grid.Column="0" x:Name="HeaderPanel">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ScrollContentPresenter Grid.Column="0" Content="{TemplateBinding ScrollViewer.Content}" />
<StackPanel Orientation="Horizontal" Grid.Column="1">
<RepeatButton Style="{StaticResource TabScrollerRepeatButtonStyle}" Content="<" Command="ScrollBar.LineLeftCommand"/>
<RepeatButton Style="{StaticResource TabScrollerRepeatButtonStyle}" Content=">" Command="ScrollBar.LineRightCommand"/>
</StackPanel>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ScrollViewer.Style>
<StackPanel x:Name="HeaderPanel" Grid.Column="0" IsItemsHost="true" Margin="2,2,2,0" Grid.Row="0" KeyboardNavigation.TabIndex="1" Panel.ZIndex="1" Orientation="Horizontal"/>
</ScrollViewer>
<Border x:Name="ContentPanel"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
Grid.Row="1"
Grid.Column="0"
Margin="2,-2, 0, 13"
KeyboardNavigation.DirectionalNavigation="Contained"
KeyboardNavigation.TabIndex="2"
KeyboardNavigation.TabNavigation="Local">
<ContentPresenter x:Name="PART_SelectedContentHost" ContentSource="SelectedContent" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</Border>
</Grid>
</ControlTemplate>
</TabControl.Template>
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem" BasedOn="{StaticResource someotherstyle}">
<Setter Property="HeaderTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="{x:Null}" Height="25">
<TextBlock Padding="10" Name="Title" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" HorizontalAlignment="Stretch" Text="{Binding Name}" ToolTip="{Binding Name}" />
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
<TabControl.ContentTemplate>
<DataTemplate>
<Grid Background="Transparent">
<ListBox x:Name="ticketView"
Unloaded="On_Listbox_enter"
ItemsSource="{Binding TicketsView}"
Background="#252525"
Margin="5,5,0,0"
HorizontalContentAlignment="Stretch"
BorderBrush="{x:Null}"
BorderThickness="1"
Padding="0,0,5,0"
VirtualizingPanel.IsVirtualizing="False"
ScrollViewer.HorizontalScrollBarVisibility="Auto"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.CanContentScroll="False"
ItemTemplate="{StaticResource TicketViewTemplate}">
<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#252525" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" />
</ListBox.Resources>
</ListBox>
<StackPanel Grid.Row="0" Margin="328,75"
Visibility="{Binding ExposeTicketSpinner, Converter={StaticResource BoolToVisConverter}}"
Width="Auto">
<Viewbox Grid.Row="0"
Height="100"
Width="100"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<WPFControls:CircularProgressBar HorizontalAlignment="Center" VerticalAlignment="Center" />
</Viewbox>
<Label Foreground="White" FontWeight="Bold" Margin="0,33" Content="Loading Tickets..." HorizontalAlignment="Center"></Label>
</StackPanel>
</Grid>
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
To get your things to work as desired, do the following:
First
Replace your Repeatbuttons with this
<RepeatButton Style="{StaticResource TabScrollerRepeatButtonStyle}" Content="<" Command="{Binding MoveLeftCommand}"/>
<RepeatButton Style="{StaticResource TabScrollerRepeatButtonStyle}" Content=">" Command="{Binding MoveRightCommand}"/>
Second
In your ViewModel (That holds the TabControl) do it like this:
public ICommand MoveLeftCommand => new RelayCommand(x => {
var currIdx = this.someobslist.IndexOf(this.ActiveTicketFilterTab);
this.ActiveTicketFilterTab = currIdx == 0 ? this.someobslist[this.someobslist.Count - 1] : this.someobslist[currIdx - 1];
});
public ICommand MoveRightCommand => new RelayCommand(x => {
var currIdx = this.someobslist.IndexOf(this.ActiveTicketFilterTab);
this.ActiveTicketFilterTab = currIdx == this.someobslist.Count - 1 ? this.someobslist[0] : this.someobslist[currIdx + 1];
});
Thats it. In case you need a RelayCommand, i can hand you mine. Of course replace my Varaibles with yours.
This Solution circles now through the TabItems
EDIT
Here is a plain scrollcycler without navigating to the TabItem, based on this <--- IMPORTANT
Add to your ScrollViewer a Loaded-Event in XAML
Here the code:
private int _scollMoverIdx = 0;
private TabControl _container;
private void ScrollViewer_OnLoaded(object sender, RoutedEventArgs e) {
this._container = (sender as ScrollViewer).TemplatedParent as TabControl;
}
public ICommand MoveLeftCommand => new RelayCommand(x => {
if (this._scollMoverIdx == 0) {
this._scollMoverIdx = this.someobslist.Count - 1;
this._container.ScrollToCenterOfView(this.someobslist[_scollMoverIdx]);
} else {
_scollMoverIdx--;
this._container.ScrollToCenterOfView(this.someobslist[_scollMoverIdx]);
}
});
public ICommand MoveRightCommand => new RelayCommand(x => {
if (this._scollMoverIdx == this.someobslist.Count - 1) {
this._scollMoverIdx = 0;
this._container.ScrollToCenterOfView(this.someobslist[_scollMoverIdx]);
} else {
_scollMoverIdx++;
this._container.ScrollToCenterOfView(this.someobslist[_scollMoverIdx]);
}
});
Its not really pretty, but i wanted to keep it simple. The linked Extension method is greate for reusability (Credits to Ray Burns). If you want this to be MVVM-conform, i suggest making a CustomControl, since scrolling from ViewModel is breaking the pattern.
Cheers

Retaining selected item in sublist in DataTemplate change in Windows Store Apps

I have generated an expandable Listview in Windows Phone 8.1. I'm switching templates on item selection changed and item click.
<ListView Name="FiltersListview" ItemContainerStyle="{StaticResource StretchItemStyle}" ItemTemplate="{StaticResource CollapsedTemplate}" SelectionChanged="FiltersListview_SelectionChanged" IsItemClickEnabled="True" ItemClick="FiltersListview_ItemClick" Grid.Row="1" Grid.ColumnSpan="2"/>
<DataTemplate x:Name="CollapsedTemplate">
<Grid Height="50">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-down.png"/>
<Rectangle Fill="Black" VerticalAlignment="Bottom" Height="1" Grid.ColumnSpan="2"/>
</Grid>
</DataTemplate>
<DataTemplate x:Name="ExpandedTemplate">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" Style="{StaticResource PageTextStyle}"/>
<Image Margin="10" Grid.Column="1" Source="/Images/arrow-up.png"/>
<ListView Margin="20,0" Grid.Row="1" RequestedTheme="Light" Grid.ColumnSpan="2" ItemsSource="{Binding SubList}" SelectionMode="Multiple">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="FontSize" Value="22"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Foreground" Value="Black"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</DataTemplate>
and then template changing
DataTemplate dtSmall, dtLarge;
private void FiltersListview_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
try
{
if (e.RemovedItems.Count > 0)
{
foreach (var item in e.RemovedItems)
{
((ListViewItem)(sender as ListView).ContainerFromItem(item)).ContentTemplate = dtSmall;
}
}
if (e.AddedItems.Count > 0)
{
foreach (var item in e.AddedItems)
{
((ListViewItem)(sender as ListView).ContainerFromItem(item)).ContentTemplate = dtLarge;
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
private void FiltersListview_ItemClick(object sender, ItemClickEventArgs e)
{
try
{
if ((sender as ListView).SelectedItem != null)
{
if ((sender as ListView).SelectedItem.Equals(e.ClickedItem))
(sender as ListView).SelectedItem = null;
else
(sender as ListView).SelectedItem = e.ClickedItem;
}
else
(sender as ListView).SelectedItem = e.ClickedItem;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
Now when expandable list is opened I want to retain the selected item status in sublist but as the template is changed and a new listview is created it is not retaining the selected items. Can somebody help?
Wow. You are sort of cracking nuts with a steamroller here. Instead of switching templates, why not create a sophisticated Data Template that when selected shows secondary content?
If you derive from ListView, you can override PrepareContainer:
public class MyListView : Windows.UI.Xaml.Controls.ListView
{
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
var item = element as Windows.UI.Xaml.Controls.ListViewItem;
base.PrepareContainerForItemOverride(element, item);
}
}
In here, you have access to the IsSelected property which you can bind to your model (just create a property) and surface in your data template. Using this value, you can switch between content in your data template.
I would use behaviors so I wouldn't have to think very hard about this. Something like this:
<Grid>
<Interactivity:Interaction.Behaviors>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="True">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Visible"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Collapsed"/>
</Core:DataTriggerBehavior>
<Core:DataTriggerBehavior Binding="{Binding IsSelected}" Value="False">
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view1}" PropertyName="Visibility" Value="Visible"/>
<Core:ChangePropertyAction TargetObject="{Binding ElementName=view2}" PropertyName="Visibility" Value="Collapsed"/>
</Core:DataTriggerBehavior>
</Interactivity:Interaction.Behaviors>
</Grid>
Since your context never really changes, neither will your List index.
Best of luck!

Categories

Resources