syncfusion winrt chart - c#

I'm trying to use a Pie Chart from the SyncFusion WinRT Studio in my new Win8 C#/XAML store app, and I can't figure out how to set the data on the chart. I have the chart on my page and have tried everything I can find to set the data to make things show up, but I can't get it to work. The sample apps aren't much help because there is 0 code in their pages and I can't figure out what's different. The chart below is copied right from their sample, but it doesn't work in my app. Anyone have any samples of using a SyncFusion chart in a WinRT app?
Chart in XAML:
<Grid Margin="30,15,30,30" x:Name="ChartGrid">
<Grid.Resources>
<local:Labelconvertor x:Key="labelconverter"/>
<Style TargetType="Line" x:Key="lineStyle">
<Setter Property="StrokeThickness" Value="0"/>
</Style>
<DataTemplate x:Key="labelTemplate">
<TextBlock Margin="10,0,0,0" Text="{Binding Converter={StaticResource labelconverter}}" FontSize="26" FontFamily="Segoe UI" FontWeight="Light" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Top" Opacity="0.5"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="legend">
<StackPanel Orientation="Horizontal">
<Grid Margin="10,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Rectangle Width="15" Height="15" Fill="{Binding Interior}"></Rectangle>
<TextBlock Margin="10,5,5,0" Grid.Column="1" Text="{Binding Item.Expense}"></TextBlock>
</Grid>
</StackPanel>
</DataTemplate>
</Grid.Resources>
<Grid.DataContext>
<local:PieChartViewModel/>
</Grid.DataContext>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<StackPanel Margin="0,0,0,20">
</StackPanel>
<chart:Chart x:Name="ScatterChart" AreaBorderThickness="0" HorizontalAlignment="Center" Grid.RowSpan="2" Visibility="Visible">
<chart:Chart.Header>
<TextBlock FontSize="20" FontFamily="Segoe UI" Margin="0,20,0,10">Agriculture Expenses Comparison</TextBlock>
</chart:Chart.Header>
<chart:Chart.PrimaryAxis>
<chart:ChartAxis></chart:ChartAxis>
</chart:Chart.PrimaryAxis>
<chart:Chart.SecondaryAxis>
<chart:ChartAxis></chart:ChartAxis>
</chart:Chart.SecondaryAxis>
<chart:Chart.Legend>
<chart:ChartLegend CornerRadius="0" ItemTemplate="{StaticResource legend}" CheckBoxVisibility="Visible" BorderThickness="1">
</chart:ChartLegend>
</chart:Chart.Legend>
<chart:PieSeries ItemsSource="{Binding Expenditure}" XBindingPath="Expense" x:Name="pieSeries" ExplodeAll="{Binding Path=IsChecked,ElementName=chkExplode}" ExplodedRadius="{Binding Path=Value,ElementName=slRadius}" Palette="Metro" Label="Expenditures" YBindingPath="Amount">
<chart:PieSeries.AdornmentsInfo>
<chart:ChartAdornmentInfo AdornmentsPosition="Bottom" HorizontalAlignment="Center" VerticalAlignment="Center" ConnectorLineStyle="{StaticResource lineStyle}" ShowConnectorLine="True" ConnectorHeight="30" ShowLabel="True" LabelTemplate="{StaticResource labelTemplate}" SegmentLabelContent="YValue">
</chart:ChartAdornmentInfo>
</chart:PieSeries.AdornmentsInfo>
</chart:PieSeries>
</chart:Chart>
</Grid>
</StackPanel>
</Grid>
Code-Behind called from the LoadState function: (I've tried all of these options and none of them work...)
PieChartViewModel pvm = new PieChartViewModel();
this.DefaultViewModel["PieChartViewModel"] = pvm;
this.DefaultViewModel["DataContext"] = pvm;
this.DefaultViewModel["Items"] = pvm;
this.DefaultViewModel["DefaultViewModel"] = pvm;
this.ScatterChart.DataContext = pvm;
this.ChartGrid.DataContext = pvm;
Object Definition:
public class PieChartViewModel
{
public PieChartViewModel()
{
this.Expenditure = new List<CompanyExpense>();
Expenditure.Add(new CompanyExpense() { Expense = "Seeds", Amount = 20d });
Expenditure.Add(new CompanyExpense() { Expense = "Fertilizers", Amount = 23d });
Expenditure.Add(new CompanyExpense() { Expense = "Insurance", Amount = 12d });
Expenditure.Add(new CompanyExpense() { Expense = "Labor", Amount = 28d });
Expenditure.Add(new CompanyExpense() { Expense = "Warehousing", Amount = 10d });
Expenditure.Add(new CompanyExpense() { Expense = "Taxes", Amount = 10d });
Expenditure.Add(new CompanyExpense() { Expense = "Truck", Amount = 10d });
}
public IList<CompanyExpense> Expenditure
{
get;
set;
}
}
public class CompanyExpense
{
public string Expense { get; set; }
public double Amount { get; set; }
}

I was able to populate the pie chart using the same data without problem. Please find the sample at PieChartDemo
Here is the document that explains how to configure Pie Chart: PieChartHelp
Following are the three APIs used for providing data for generating PieSeries,
ItemsSource - You can provide the data source using this property. Any IEnumerable can be given as data source.
XBindingPath - It is used to provide the path for category data in the source object.
YBindingPath - It is used to provide the path for numeric data in the source object.

Related

Draw variable number of rectangles within WPF Grid cells?

I have a WPF Grid which is 3 columns wide and 8 rows:
<Window x:Class="Container.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="700" Width="1000">
<Grid ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
<RowDefinition Height="20"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10*" />
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10*" />
</Grid.ColumnDefinitions>
</Grid>
</Window>
I am using this to draw something like this:
Every cell in the first and third columns may have a different number of rectangles. Also, the width of each rectangle may be different and change at run-time. The width will be proportionate to a number (known at run-time and continually-changing).
What is the best way to draw these rectangles?
Here is what I've come up with after about an hour of fiddling (GitHub Repo):
I'm using the MVVM pattern to make the UI as easy as possible. Right now, it just populates with some random data.
The XAML:
<Window
x:Class="BuySellOrders.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:local="clr-namespace:BuySellOrders"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="MainWindow"
Width="800"
Height="450"
mc:Ignorable="d">
<Window.DataContext>
<local:MainWindowVm />
</Window.DataContext>
<Grid Margin="15">
<ItemsControl ItemsSource="{Binding Path=Prices}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="1" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:PriceEntryVm}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border
Grid.Column="0"
Padding="5"
HorizontalAlignment="Stretch"
BorderBrush="Black"
BorderThickness="1">
<ItemsControl HorizontalAlignment="Right" ItemsSource="{Binding Path=BuyOrders}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:OrderVm}">
<Border
Width="{Binding Path=Qty}"
Margin="5"
Background="red"
BorderBrush="Black"
BorderThickness="1" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
<Border
Grid.Column="1"
BorderBrush="Black"
BorderThickness="1">
<TextBlock
Margin="8"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="{Binding Path=Price}" />
</Border>
<Border
Grid.Column="2"
Padding="5"
BorderBrush="Black"
BorderThickness="1">
<ItemsControl ItemsSource="{Binding Path=SellOrders}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type local:OrderVm}">
<Border
Width="{Binding Path=Qty}"
Margin="5"
Background="red"
BorderBrush="Black"
BorderThickness="1" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Border>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Grid>
</Window>
The view models:
class MainWindowVm : ViewModel
{
public MainWindowVm()
{
var rnd = new Random();
Prices = new ObservableCollection<PriceEntryVm>();
for (int i = 0; i < 8; i++)
{
var entry = new PriceEntryVm();
Prices.Add(entry);
entry.BuyOrders.CollectionChanged += OnOrderChanged;
entry.SellOrders.CollectionChanged += OnOrderChanged;
entry.Price = (decimal)110.91 + (decimal)i / 100;
var numBuy = rnd.Next(5);
for (int orderIndex = 0; orderIndex < numBuy; orderIndex++)
{
var order = new OrderVm();
order.Qty = rnd.Next(70) + 5;
entry.BuyOrders.Add(order);
}
var numSell = rnd.Next(5);
for (int orderIOndex = 0; orderIOndex < numSell; orderIOndex++)
{
var order = new OrderVm();
order.Qty = rnd.Next(70) + 5;
entry.SellOrders.Add(order);
}
}
}
private void OnOrderChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (var item in e.NewItems)
{
var order = item as OrderVm;
if (order.Qty > LargestOrder)
{
LargestOrder = order.Qty;
}
}
}
}
private int _largestOrder;
public int LargestOrder
{
get { return _largestOrder; }
private set { SetValue(ref _largestOrder, value); }
}
public ObservableCollection<PriceEntryVm> Prices { get; }
}
public class PriceEntryVm: ViewModel
{
public PriceEntryVm()
{
BuyOrders = new OrderList(this);
SellOrders = new OrderList(this);
}
private Decimal _price;
public Decimal Price
{
get {return _price;}
set {SetValue(ref _price, value);}
}
public OrderList BuyOrders { get; }
public OrderList SellOrders { get; }
}
public class OrderList : ObservableCollection<OrderVm>
{
public OrderList(PriceEntryVm priceEntry)
{
PriceEntry = priceEntry;
}
public PriceEntryVm PriceEntry { get; }
}
public class OrderVm : ViewModel
{
private int _qty;
public int Qty
{
get { return _qty; }
set { SetValue(ref _qty, value); }
}
}
I had to make some assumptions about the naming of things, but hopefully you should get the basic idea of what's going on.
It's structured as a list of PriceEntry, each of which contains a Price, and a BuyOrders and SellOrders properties.
BuyOrders and SellOrders are just lists of orders that have a Quantity property.
The XAML binds the list of price entries to a template that contains a 3 column grid. The first and 3rd columns of that grid bound to another set of item controls for each list of orders. The template for each order is just a border with a Width bound to the Quantity of the order.
All the binds means that just updating a property, or adding an order to either the buy or sell list of a price entry will automatically propagate to the UI. Adding or removing a PriceEntry will also automatically adjust the UI.
I haven't implemented your automatic scaling yet, but the basic idea would be to use a ValueConverter on the Quantity binding, to make it automatically adjust to the largest order.
As an extra note, it uses this nuget package to provide some of the MVVM boiler-plate code, but you should be able to use anything you want, as long as it gives you INotifyPropertyChanged support.
Here is a bonus screen capture showing the dynamic nature of MVVM updating the UI based on a timer.
This only needed a few lines of code to randomly pick a row, then randomly pick an order on the row, then add or subtract a small random amount from the quantity.
_updateTimer = new DispatcherTimer();
_updateTimer.Tick += OnUpdate;
_updateTimer.Interval = TimeSpan.FromSeconds(0.01);
_updateTimer.Start();
private void OnUpdate(object sender, EventArgs e)
{
var entryIndex = _rnd.Next(Prices.Count);
var entry = Prices[entryIndex];
OrderList list;
list = _rnd.Next(2) == 1 ?
entry.BuyOrders :
entry.SellOrders;
if (list.Any())
{
var order = list[_rnd.Next(list.Count)];
order.Qty += _rnd.Next(0, 8) - 4;
}
}
Right then, here goes....
This is exactly the kind of thing you want to use data-binding for. You can try and do things manually if you like, but your code will quickly become very messy if you do. WPF lets you do things the old-school way (i.e. similar to WinForms et al) but that was really to facilitate porting of legacy code. I won't go into too much detail about MVVM (plenty of info on the net about it), but you can get started by using NuGet to add MVVMLightLibs or some other MVVM framework to your project and then you assign your main window a view model by doing something like this:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
}
}
So now it's time for the view model itself, which is a model of the data structures that you want your view to display:
public class MainViewModel : ViewModelBase
{
public ObservableCollection<PriceLevel> PriceLevels { get; } = new ObservableCollection<PriceLevel>
{
new PriceLevel(110.98, new int[]{ }, new int[]{ }),
new PriceLevel(110.97, new int[]{ }, new int[]{ }),
new PriceLevel(110.96, new int[]{ }, new int[]{ }),
new PriceLevel(110.95, new int[]{ }, new int[]{ 5 }),
new PriceLevel(110.94, new int[]{ }, new int[]{ 3, 8 }),
new PriceLevel(110.93, new int[]{ 8, 3, 5, }, new int[]{ }),
new PriceLevel(110.92, new int[]{ 3 }, new int[]{ }),
new PriceLevel(110.91, new int[]{ }, new int[]{ }),
};
}
public class PriceLevel
{
public double Price { get; }
public ObservableCollection<int> BuyOrders { get; }
public ObservableCollection<int> SellOrders { get; }
public PriceLevel(double price, IEnumerable<int> buyOrders, IEnumerable<int> sellOrders)
{
this.Price = price;
this.BuyOrders = new ObservableCollection<int>(buyOrders);
this.SellOrders = new ObservableCollection<int>(sellOrders);
}
}
If you don't already know, ObservableCollection is very similar to list but it propegrates change notification, so when you make your view display the data in it your GUI will update automatically whenever the list changes. This MainViewModel class contains an ObservableCollection of type PriceLevel, and each PriceLevel contains the price and the lists of buy and sell orders. This means you'll be able to add and remove price points, and also add and remove the orders in the price points, and your front-end will reflect those changes.
So on to the front end itself:
<Window.Resources>
<!-- Style to display order list as horizontal list of red rectangles -->
<Style x:Key="OrderListStyle" TargetType="{x:Type ItemsControl}">
<!-- Set ItemsPanel to a horizontal StackPanel -->
<Setter Property="ItemsPanel">
<Setter.Value>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</Setter.Value>
</Setter>
<!-- Display each item in the order list as a red rectangle and scale x by 8*size -->
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Border BorderBrush="Black" BorderThickness="1" Margin="5" >
<Rectangle Width="{Binding}" Height="20" Fill="Red">
<Rectangle.LayoutTransform>
<ScaleTransform ScaleX="8" ScaleY="1" />
</Rectangle.LayoutTransform>
</Rectangle>
</Border>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- Style to make Price cells vertically aligned -->
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid Background="{TemplateBinding Background}">
<ContentPresenter VerticalAlignment="Center" />
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<!-- This style centers the column's header text -->
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center" />
</Style>
</Window.Resources>
<!-- This datagrid displays the main list of PriceLevels -->
<DataGrid ItemsSource="{Binding PriceLevels}" AutoGenerateColumns="False" IsReadOnly="True"
CanUserAddRows="False" CanUserDeleteRows="False" CanUserReorderColumns="False" CanUserResizeColumns="False"
CanUserResizeRows="False" CanUserSortColumns="False" RowHeight="30">
<DataGrid.Columns>
<!-- The buy orders column -->
<DataGridTemplateColumn Header="Buy orders" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding BuyOrders}" Style="{StaticResource OrderListStyle}" HorizontalAlignment="Right" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<!-- The price column -->
<DataGridTextColumn Header="Price" Width="Auto" Binding="{Binding Price}" />
<!-- The sell orders column -->
<DataGridTemplateColumn Header="Sell Orders" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ItemsControl ItemsSource="{Binding SellOrders}" Style="{StaticResource OrderListStyle}" HorizontalAlignment="Left" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Looks a bit full-on, but if you break it down into sections it's actually pretty straightforward. The main different between this and what you've been trying to do is that I'm using a DataGrid. This is basically a Grid control that's had extra functionality added to make it respond dynamically to data that it's been bound to. It also has a lot of extra stuff we dont' need (editing, column resize/reordering etc) so I've turned all that off. The DataGrid binds to PriceLevels in the view model, so it will display a vertical list showing each one. I've then explicitly declared the 3 columns you're after. The middle one is easy, it's just text, so DataGridTextColumn will, do the job. The other two are horizontal arrays of rectangles, so I've used DataGridTemplateColumn which allows me to customize exactly how they look. This customization is mostly done in the OrderListStyle at the very top of the XAML which sets ItemsPanel to a horizontal StackPanel and sets ItemTemplate to a rectangle. There's also a bit of XAML in there to scale the rectangle by a constant, according to the value of the integer it's displaying in the order list.
Here's the result:
I know the XAML might seem a little full-on, but keep in mind this is now fully data-bound to that view model and it will automatically update in response to changes. This little bit of extra work at the start results in MUCH cleaner update code which is also easier to test and debug.
Hope this is what you're after, if you have any questions let me know and we can take it into chat.
UPDATE: If you want to see the dynamic update in action then add this to your main view model's constructor, it just adds and removes orders randomly:
public MainViewModel()
{
var rng = new Random();
var timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(0.1);
timer.Tick += (s, e) =>
{
var row = this.PriceLevels[rng.Next(this.PriceLevels.Count())]; // get random row
switch (rng.Next(4))
{
case 0: row.BuyOrders.Add(1 + rng.Next(5)); break;
case 1: row.SellOrders.Add(1 + rng.Next(5)); break;
case 2: if (row.BuyOrders.Count() > 0) row.BuyOrders.RemoveAt(rng.Next(row.BuyOrders.Count())); break;
case 3: if (row.SellOrders.Count() > 0) row.SellOrders.RemoveAt(rng.Next(row.SellOrders.Count())); break;
}
};
timer.Start();
}

How to display array in xaml under UWP C#

How to display array in xaml the way that each line is on separate row and each row is split into separate textblocks?
I split line like so:
string[] splitLines = line.Split(';');
itemsControl.Items.Add(line);
Then, in xaml I display it like so:
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding itemsControl}"
FontSize="24">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="Auto"
Margin="0 12"
HorizontalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk0" Text="{Binding }" />
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
This way I get each line from my .xls file in separate row, but the separator ';' is included in the returned content of row.
Now I would like to remove ';' separator and put each word from each line on separate textblock, like so:
for (int index = 0; index < splitLines.Length; index++)
{
itemsControl.Items.Add(splitLines[index]);
}
This breaks each line into separate words, but unfortunately, each word is put on separate row(instead to populate 5 textblocks with each line's words.
Any idea how to show each .xls line in separate row, but then also split each line into words and put them in separate textblocks in separate columns?
EDIT
I have tried the solution from Alexej Sommer, I get some erors though:
ItemsData dataitem = new ItemsData
{
value0 = splitLines[0];
value1 = splitLines[1];
value2 = splitLines[2];
value3 = splitLines[3];
value4 = splitLines[4];
}
items.Add(dataitem);
In this piece of code I get first semicolon underscored and error says:
} expected.
Then, values 1 - 4 are underscored and error says:
The name (X) does not exist in the current content
At last, dataitem gets underscored and same error shows up.
EDIT 2 --
I managed to fix the problem. There were problems with braces and code put in a wrong place. Also, instead of:
ItemsData dataitem = new ItemsData
{
value0 = splitLines[0];
value1 = splitLines[1];
value2 = splitLines[2];
value3 = splitLines[3];
value4 = splitLines[4];
}
items.Add(dataitem);
I used:
ItemsData dataitem = new ItemsData
{
value0 = splitLines[0],
value1 = splitLines[1],
value2 = splitLines[2],
value3 = splitLines[3],
value4 = splitLines[4],
};
items.Add(dataitem);
And that solved the problem.
Here is clean working code:
public async void ReadFile()
{
var path = #"CPU.xls";
var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
var file = await folder.GetFileAsync(path);
var readFile = await Windows.Storage.FileIO.ReadLinesAsync(file);
foreach (string line in readFile.OrderBy(line =>
{
int lineNo;
var success = int.TryParse(line.Split(';')[4], out lineNo);
if (success) return lineNo;
return int.MaxValue;
}))
{
string[] splitLines = line.Split(';');
ObservableCollection<ItemsData> items = new ObservableCollection<ItemsData>();
for (int index = 0; index < splitLines.Length; index++)
{
ItemsData dataitem = new ItemsData
{
value0 = splitLines[0],
value1 = splitLines[1],
value2 = splitLines[2],
value3 = splitLines[3],
value4 = splitLines[4],
};
items.Add(dataitem);
}
itemsControl.DataContext = items;
}
}
I yet need to fix the layout as for now all the textblocks show up in same column and they overlap.
Thank you Alexej for your help!
Edit 3----
To put textblocks on separate columns in xaml I did like so:
<ScrollViewer>
<ItemsControl x:Name="itemsControl"
ItemsSource="{Binding}"
FontSize="24">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid Width="Auto"
Margin="0 12"
HorizontalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<StackPanel Grid.Column="0"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk0" Text="{Binding value0}" />
</StackPanel>
<StackPanel Grid.Column="1"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk1" Text="{Binding value1}" />
</StackPanel>
<StackPanel Grid.Column="2"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk2" Text="{Binding value2}" />
</StackPanel>
<StackPanel Grid.Column="3"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk3" Text="{Binding value3}" />
</StackPanel>
<StackPanel Grid.Column="4"
Grid.Row="0"
Orientation="Horizontal">
<TextBlock Name="txtblk4" Text="{Binding value4}" />
</StackPanel>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
This way each word from line is put on separate column. TextBlocks don't overlap anymore.
Unfortunately I didn't manage do showcase all file(all lines). For now each row in xaml is populated with same line from the file instead of pulling each line into separate rows in xaml.
What should I do in order to list all lines instead of just one line?
I believe that there is problem on C# code side.
First create class for data:
public class itemsdata
{
public string txt0 { get; set; }
public string txt1 { get; set; }
public string txt2 { get; set; }
public string txt3 { get; set; }
public string txt4 { get; set; }
}
after it, create collection
ObservableCollection<itemsdata> items = new ObservableCollection<itemsdata>();
and fill it:
for (int index = 0; index < splitLines.Length; index++)
{
itemsdata dataitem=new itemsdata
{
txt0=splitLines[0];
txt1=splitLines[1];
txt2=splitLines[2];
txt2=splitLines[3];
txt2=splitLines[4];
}
items.Add(dataitem);
}
itemsControl.DataContext = items;
change binging to
ItemsSource="{Binding}"
and add new fields to datatemplate
<TextBlock Name="txtblk0" Text="{Binding txt0}" />
<TextBlock Name="txtblk1" Text="{Binding txt1}" />
<TextBlock Name="txtblk2" Text="{Binding txt2}" />
<TextBlock Name="txtblk3" Text="{Binding txt3}" />
<TextBlock Name="txtblk4" Text="{Binding txt4}" />

How can I get the following value of the property in a TextBlock which has its source as Data Binding in a Windows Phone application

Please have a look at this image to understand my scenario
So I have the above scenario in my Windows Phone application where I have a ListBox with the below layout.
My XAML for the ListBox
<ListBox x:Name="llsIceCreamBrands" Margin="0,54,0,0" CacheMode="BitmapCache">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="0,0,0,40">
<StackPanel>
<Border BorderBrush="{StaticResource PhoneProgressBarBackgroundBrush}" BorderThickness="3">
<Image Width="200" Height="200" Source="{Binding IceCreamBrandImage }" Margin="3,0,0,0" Stretch="Fill"/>
</Border>
</StackPanel>
<StackPanel>
<Grid Margin="20,-5,0,0" Height="250" >
<StackPanel>
<TextBlock Text="{Binding IceCreamBrandName }" FontWeight="SemiBold" FontSize="34" FontFamily="Segoe WP" Margin="0" TextWrapping="Wrap" Width="184" VerticalAlignment="Top" HorizontalAlignment="Left" Opacity="1" LineStackingStrategy="BlockLineHeight" LineHeight="35" Height="Auto" />
<TextBlock Text="{Binding IceCreamBrandFlavour }" FontWeight="Normal" FontSize="15" FontFamily="Segoe WP" TextWrapping="Wrap" VerticalAlignment="Top" Width="200" Opacity="0.7" HorizontalAlignment="Left" IsHitTestVisible="False" Height="140"/>
</StackPanel>
</Grid>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
In C# Code:
void GetIceCreamBrands()
{
string mystring = "";
for (int i = 0; i < dc.IceCreams[cID].Brands.Count; i++)
{
var bmp = new BitmapImage();
if (dc.IceCreams[cID].Brands[i].HasArt)
{
bmp.SetSource(dc.IceCreams[cID].Brands[i].GetImage());
}
else
{
bmp.CreateOptions = BitmapCreateOptions.None;
bmp.UriSource = new Uri("/Assets/Images/IceCreams/Placeholder.png", UriKind.Relative);
}
for (int j = 0; j < dc.IceCreams[cID].Brands.Count; j++)
{
for (int k = 0; k < dc.IceCreams[cID].Brands[j].Flavour.Count; k++)
{
sourceFlavourList.Add(new Flavour
{
FlavourBrand = dc.IceCreams[cID].Brands[j].Name,
BrandFlavourName = dc.IceCreams[cID].Brands[j].Flavour[k].Name
});
}
}
sourceIceCreamBrands.Add(new IceCreamBrands
{
IceCreamBrandName = dc.IceCreams[cID].Brands[i].Name,
IceCreamBrandImage = bmp,
IceCreamBrandFlavour = "Get Flavours here for the particular brand somehow?"
});
}
llsIceCreamBrands.ItemsSource = sourceIceCreamBrands.ToList();
}
I have the above method in my code which successfully gets the brands and their images, but the flavours are also a Collection which I tried to get in a single string by using
string mystring = string.Join(Environment.NewLine, sourceFlavourList.Select(x => x.IceCreamBrandFlavourName));
But this returns the same values for both Ben&Jerrys and Haagen-Dazs - which is an amalgamation of both brands' flavours.
How can I achieve what I'm looking for?
I don't see where you define the variable 'sourceFlavourList' within GetIceCreamBrands(), so I assume you have this defined elsewhere in your code. This would explain why you see the full list of flavours (from both brands) as you keep adding all flavours to this one variable.
So instead of using this full list variable, you would need to bind to a per brand list (which you DO have in your result)., so you can use the same linq you have, but with a different source variable).
Try something like this:
var flavours = string.Join(Environment.NewLine, dc.IceCreams[cID].Brands[j].Flavour.Select(x => x.Name));
sourceIceCreamBrands.Add(new IceCreamBrands
{
IceCreamBrandName = dc.IceCreams[cID].Brands[i].Name,
IceCreamBrandImage = bmp,
IceCreamBrandFlavour = flavours
});

ListBox items not displaying

so i am working on a Windows Phone 7 application, and i am having a problem, normally in my other WPF/WinForm applications this code would work but here on Wphone 7 i am receiving a problems, i created data class:
public class AlarmTemplate
{
public string Name { get; set; }
public string Time { get; set; }
public BitmapImage Activated { get; set; }
public AlarmTemplate(string name, string time, string activated)
{
Name = name;
Time = time;
Activated = new BitmapImage
{UriSource = new Uri("Images/alarm_" + activated + ".png", UriKind.RelativeOrAbsolute)};
}
}
Next thing read dad, also i tried with hard coding data and its not working:
private List<AlarmTemplate> _templateList = new List<AlarmTemplate>();
private void PopulateList()
{
using (var storage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!storage.FileExists("file.txt"))
return;
using (var reader = new BinaryReader(storage.OpenFile("file.txt", FileMode.Open)))
{
var s = reader.ReadInt32();
for (var i = 0; i < s; i++)
{
_templateList.Add(new AlarmTemplate(reader.ReadString(), reader.ReadString(),
reader.ReadString()));
}
}
}
lbAlarms.ItemsSource = _templateList;
}
Here is xaml:
<ListBox Height="176.135" HorizontalAlignment="Left" Margin="0,567.164,0,0" Name="lbAlarms" VerticalAlignment="Top" Width="456" Foreground="#FFFFC7C7" ItemsSource="{Binding}" Background="Transparent" AllowDrop="False" BorderThickness="1" BorderBrush="#00900707" Grid.Row="1" Hold="lbAlarms_Hold">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Grid.Row="1" Height="52" Orientation="Horizontal" Name="spList" VerticalAlignment="Top" Width="480" Margin="0,329,0,0" UseLayoutRounding="False">
<Image Height="52" Name="imTStatus" Stretch="Uniform" Width="73" Margin="10,0,0,0" UseLayoutRounding="False" Source="{Binding Activated}" />
<StackPanel Height="52" Name="spHolder" Width="300" Margin="10,0,0,0" VerticalAlignment="Stretch" HorizontalAlignment="Left" UseLayoutRounding="False">
<TextBlock Height="26" Name="tbTTime" Text="{Binding Time}" Foreground="Black" FontFamily=".\Fonts\Nokia.ttf#Nokia" TextAlignment="Left" FontWeight="Bold" Width="230" FontSize="24" HorizontalAlignment="Left" UseLayoutRounding="False" />
<TextBlock Height="26" Name="tbTName" Text="{Binding Name}" Foreground="Black" FontFamily=".\Fonts\Nokia.ttf#Nokia" HorizontalAlignment="Left" Width="297" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Your code is working (I noticed the scrollbar was present on the right), but your text colour is black on black so not very visible.
Get rid of the TextBlock colour Foreground="Black" :)
Note, your margin means your listbox is very small at the bottom of the page, less than 1 item high, so you might want to change that as well.
private List<AlarmTemplate> _templateList = new List<AlarmTemplate>();
public List<AlarmTemplate> TemplateList
{
get { return _templateList; }
set { _templateList = value; }
}
and set the binding to TemplateList.

How to bind data to a ListBox in a ControlTemplate?

What I am trying to do is to create some sort of "rooms"(like a chat group, a sharing center or whatever you want). All the room are created the same way, but each one of them contains different informations. Each of these rooms is contained in a TabItem. I managed to create dynamically all the Tabitems, to give those a Grid and a Canvas. But at the moment I am facing a problem: I created a ControlTemplate Called RoomMenu that will show different buttons and, the most important, the people connected in this room in a ListBox(I retrieve those people from a WebService each time I change the selected Tabitem). But since my ListBox is in a ControlTemplate I have no idea how to access the ListBox ItemSource to bind a generic List to it. Down Below is the code used to create my rooms and their content.
Here is my room menu class:
public class RoomMenu : ContentControl
{
public RoomMenu()
{
DefaultStyleKey = typeof(RoomMenu);
}
public string Current_room_id;
public string FullName;
public string Rights;
}
And here is the ControlTemplate located in generic.xaml:
<Style TargetType="test:RoomMenu">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="test:RoomMenu">
<Grid x:Name="MenuGrid">
<Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" BorderBrush="Black" CornerRadius="2" Background="Black">
<StackPanel Orientation="Vertical">
<Border x:Name="Room_friend_border" Background="Gray" CornerRadius="4" Margin="5">
<ListBox x:Name="current_room_friends" ItemsSource="{Binding ''}" Margin="5" Height="230">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FullName}" Height="20"/>
<TextBlock Text="{Binding Rights}" Height="20"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
<Border x:Name="Room_menu" Background="Gray" CornerRadius="4" Margin="5">
<StackPanel Orientation="Vertical" Margin="10">
<Button Content="Add item" Margin="0,2,0,2"/>
<Button Content="Set changes" Margin="0,2,0,2"/>
<Button Content="Invite friend" Margin="0,2,0,2"/>
<Button Content="Rename room" Margin="0,2,0,2"/>
<Button Content="Delete room" Margin="0,2,0,2"/>
</StackPanel>
</Border>
</StackPanel>
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Here is my Dictionnary Class that contains the RoomMenu:
public class Rooms : TabItem
{
public string Room_guid;
public string Room_name;
public string Primary_user_guid;
public string Room_version;
public Grid Room_grid;
public Canvas Room_canvas;
public RoomMenu Room_menu;
}
And this is when I call my ControlTemplate and Add it to my TabItem's Grid:
public void Set_rooms_interface()
{
foreach (KeyValuePair<string, Rooms> kvp in rooms_list)
{
rooms_list[kvp.Key].Room_menu = new RoomMenu();
rooms_list[kvp.Key].Room_canvas = new Canvas();
rooms_list[kvp.Key].Room_grid = new Grid();
//instance grid columns
rooms_list[kvp.Key].Room_grid.ColumnDefinitions.Add(new ColumnDefinition() {Width = new GridLength(900)});
rooms_list[kvp.Key].Room_grid.ColumnDefinitions.Add(new ColumnDefinition());
//Refreshing room canvas
rooms_list[kvp.Key].Room_canvas.Height = rooms_list[kvp.Key].Room_grid.ActualHeight;
rooms_list[kvp.Key].Room_canvas.Width = rooms_list[kvp.Key].Room_grid.ActualWidth;
rooms_list[kvp.Key].Room_canvas = refresh_canvas(kvp.Key);
Grid.SetColumn(rooms_list[kvp.Key].Room_canvas, 0);
Grid.SetColumn(rooms_list[kvp.Key].Room_menu, 1);
//Add Canvas to Grid
rooms_list[kvp.Key].Room_grid.Children.Add(rooms_list[kvp.Key].Room_canvas);
rooms_list[kvp.Key].Room_grid.Children.Add(rooms_list[kvp.Key].Room_menu);
//Setting TabItem Name
rooms_list[kvp.Key].Header = rooms_list[kvp.Key].Room_name;
//Adding Grid to TabItem.Content
rooms_list[kvp.Key].Content = rooms_list[kvp.Key].Room_grid;
//Adding TabItem to TabControl
Room_tab.Items.Add(kvp.Value);
}
}
I'm sorry if the whole question is a bit long but it was the only way to explain clearly what I was trying to do. So if anyone could give me a hint or answer to do some databinding in a ControlTemplate it would greatly help me.
Thank You.
I think you started in the wrong direction when instantiating UI elements in code. The code behind should only contain one line assigning the people list to the current_room_friends DataContext.
Start with simpler examples of binding data to a ListBox like the beautiful planet example of Bea Stollnitz.

Categories

Resources