Padding text in listbox - wpf

var a1 = "HEL";
var a2 = "HELLO";
var a3 = "LLO";
var length = a2.Length+5;
listbox.Items.Add(a1.PadRight(length) +"End");
listbox.Items.Add(a2.PadRight(length) + "End");
listbox.Items.Add(a3.PadRight(length) + "End");
I have code like this to obviously pad all text so that the word End lines up.
The problem is I have to change the font from the wpf listbox from Segoe UI to Courier New to have this work. The rest of my app uses Segoe UI, so I think it looks weird here.
Is there any way to achieve the result with Segoe UI or maybe a similar font with correct spacing I could use, or maybe someone has some other smart solution i haven't even thought of? :-)
Thanks
edit
at the end of the day I want this to display to related items like this:
ITEM A -> ITEM B
ITEM X -> ITEM Y
ITEM C -> ITEM E
dont want to use gridview.

Feed the ListBox the two pieces of data separately, and use a data template. Here's how.
First, create a little class to represent each item you want to insert:
public class WordPair {
public string First { get; set; }
public string Second { get; set; }
}
(You probably already have a suitable class and/or collection in your application -- I assume those pairs of strings are coming from somewhere!)
Second, set your ListBox.ItemsSource to a collection of these things:
listBox.ItemsSource = new List<WordPair> {
new WordPair { First = "ITEM A", Second = "ITEM B" },
new WordPair { First = "ITEM X", Second = "ITEM Y" },
};
Again, this collection may already exist in your app.
Third, create a DataTemplate specifying the desired layout, and assign it to your ListBox.ItemTemplate:
<!-- in your Window.Resources section -->
<DataTemplate x:Key="AlignedPairs">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding First}" Grid.Column="0" />
<TextBlock Text="->" TextAlignment="Center" Grid.Column="1" />
<TextBlock Text="{Binding Second}" TextAlignment="Right" Grid.Column="2" />
</Grid>
</DataTemplate>
<ListBox Name="listBox" ItemTemplate="{StaticResource AlignedPairs}">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
(I've guessed at the exact alignment you want for the items, but you can obviously tweak it.)
Note that you also need to set the HorizontalContentAlignment of the ListBoxItems to Stretch using ListBox.ItemContainerStyle. Otherwise each ListBoxItem will take up only the space it needs, resulting in all the Grid columns being minimal size and looking like a straight concatenation. Stretch makes each ListBoxItem fill the full width so the Grid columns are forced to grow accordingly.

<ListBox
x:Name="listBox" HorizontalContentAlignment="Right"/>
check it :)

Related

Displaying a list of images that just fill their available space in an expandable cell

I've got a desktop GUI (VS2013, .NET 4.5.2) with a few levels of embedded grids. In one cell (which can be expanded in both dimensions using gridsplitters) I have this:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ListView Grid.Column="0" ItemsSource="{Binding Results.Info}"/>
<ListView Grid.Column="1" ItemsSource="{Binding Results.Images}"/>
</Grid>
In the MVVM-Light-supported view model:
public ObservableCollection<object> Images
{
get { return mImages; }
set { Set(() => Images, ref mImages, value); }
}
I load up this property with a sequence of text (captions) and images created this way:
var img = new Image
{
Source = new BitmapImage(new Uri(fullPathToPng)),
};
Images.Add(caption);
Images.Add(img);
...repeat until all captions and images added
The code above produces images large enough to cause the listview to display scrollbars, although dragging gridsplitters eventually lets me see whole images.
Here's what I'd like to happen: The images shrink to fill just the available space without causing the listview to display its scrollbars, and when gridsplitters are moved giving this cell more space, the images grow to fill just the newly-available space.
I'm not married to using a ListView to hold the captions/images sequence, but I do want the solution to respect MVVM. Thanks.
Turned out to be simple: I just needed to disable the ListView's horizontal scrolling:
<ListView Grid.Column="1" ItemsSource="{Binding Results.Images}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" />

how to measure UIElement created from hierachical datatemplate

folks, I am about to print a hierachical data from Silverlight 5. I use a resource dictionary to define the layout of the data. The main xaml segments like this:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:MSCE.SL.ArchievementAssessment"
xmlns:stat="clr-namespace:MSCE.SL.ArchievementAssessment.Statistics">
<DataTemplate DataType="stat:Level1">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
<ItemsControl Grid.Column="1" ItemsSource="{Binding Children}"/>
</Grid>
</DataTemplate>
<DataTemplate DataType="stat:Level2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
<ItemsControl Grid.Column="1" ItemsSource="{Binding Children}"/>
</Grid>
</DataTemplate>
<DataTemplate x:Key="Level3ItemTemplate">
....
</DataTemplate>
<DataTemplate DataType="stat:Level3">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="auto"/>
<ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center"/>
<ListBox Grid.Column="1" ItemsSource="{Binding Children}"
ItemTemplate="{StaticResource Level3ItemTemplate}"/>
</Grid>
</DataTemplate>
</ResourceDictionary>
then I use those templates in printing code as follow:
void Print(object para)
{
PrintDocument pd = new PrintDocument();
List<FrameworkElement> pages = null;
int pageIndex = 0;
pd.PrintPage += (s, e) =>
{
if (pages == null)
{
pages = CreatePages(e.PrintableArea);
}
e.PageVisual = pages[pageIndex] ;
pageIndex++;
e.HasMorePages = pageIndex < pages.Count;
};
pd.Print("statistics");
}
List<FrameworkElement> CreatePages(Size printableArea)
{
// create result pages' container
List<FrameworkElement> pages=new List<FrameworkElement>();
// get resources for printing
IEnumerable<Level1> data=...// detail ignored, get data from ViewModel
ResourceDictionary res=... // detail ignored, get data template from assembly
// create page root visual and
// merge printing templates' resource into root's resource dictionary
StackPanel root=new StackPanel();
root.ResourceDictionary.MergedDictionaries.Add(res);
// fetch data template of data Level1
var level1Template=root.Resources[new DataTemplateKey(typeof(Level1))] as DataTemplate;
// trace height of available space
double availableContentHeight=printableArea.Height;
foreach(var lvl1 in data)
{
// create UI of Level1 using template
var ui=level1Template.LoadContent() as FrameworkElement;
ui.DataContext = data;
ui.OnApplyTemplate();
// measure the size requirement of this Level1's UI
ui.Measure(printableArea);
// if available space is not enough, add the last page to pages container
// and create a new page to contain new created Level1 UI
if(ui.DesireSize.Height>availableContentHeight)
{
pages.Add(root);
root=new StackPanel();
availableContentHeight=printableArea.Height;
}
root.Children.Add(ui);
availableContentHeight-=ui.DesiredSize.Height;
}
pages.Add(root);
return pages;
}
The problem occurs at Measuring. It should contain about three pages. But the sum of the heights of all Level1 UIs based on Measure results occupy only half a page. So the printer prints always only one page and cuts many content down. I think that the Measure method for Level1 UI returns only the height of his title(TextBlock Text="{Binding Name}"), it doesn't include the space requirements of level1's children and certainly the space requirements of level2's children.
At the begining, I didn't put the statement ui.OnApplyTemplate(). After the problem occured, I thought that this might preload all children content and I could get right measuring result. But in the fact it changes nothing.
Now, my thought is, either preloading the whole visual tree for data Level1 before adding it to PageVisual of PringPageEventArgs to get right measuring result, or write a hierachical measuring method to measure Level1 UI from the bottom (level3's children) to top.
Because that my actual data templates are more complicated than the above ones, the second method is time comsumed and is prone to introduce bugs. So I hope someone to teach me how to accomplish the first road or direct me to a clear solution.
Well, after some days, I had to handle the measuring problem with proximate algorithm. I assume that every detailed level3 row occupys only one row and then measure height of each row and sum all height values up. Without accruate measuring, not perfect, but It can cope with the case.

Add items to ItemsControl

I have an application for telephone call. Each call(line) has its own unique information. Say a colorful icon plus and line number. The numbers are in a queue, I used parallel programming skills to deal these items. When processing the item, the information is shown on the screen. Here I prefer ItemsControl.
The expected result likes the image. I want to
I borrowed the code for phone icon.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>
<SolidColorBrush x:Key="RedBrush" Color="Red" />
<SolidColorBrush x:Key="AmberBrush" Color="#FFFFC500" />
<SolidColorBrush x:Key="GreenBrush" Color="Green" />
<Geometry x:Key="PhoneIcon">F1M52.5221,11.1016C52.0637,10.6796 44.4973,4.55737 29.4347,12.7369 26.3098,14.4296 23,17.224 20.095,20.1692 17.1497,23.073 14.3555,26.3842 12.6626,29.509 4.48303,44.5703 10.6093,52.1393 11.0298,52.5962 11.0298,52.5962 12.9778,55.5885 14.7057,53.8579L23.3555,45.2134C24.897,43.6692 22.7721,39.2134 18.2563,39.3541 17.1301,39.3906 15.5481,38.9531 17.0571,35.5156 18.3945,32.4623 22.3436,27.4766 24.8879,24.9648 27.4048,22.418 32.3904,18.4713 35.4426,17.1301 38.8787,15.6223 39.3175,17.2031 39.2811,18.332 39.1393,22.8462 43.5962,24.9686 45.1366,23.4283L53.7864,14.7787C55.5142,13.052,52.5221,11.1016,52.5221,11.1016z</Geometry>
My question: If I know the color of the phone icon and the phone number, how to add it to the itemscontrol? The phone number needs to be bind, I assume I have a class:
public class Lines
{
public string color { get; set; }
public string linenumber { get; set; }
}
And I defined the ItemsControls as:
<DockPanel>
<ItemsControl Height="300">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
Not sure the next step?
Assuming you are not using MVVM here, just XAML forms with code behind classes - you need to alter your code behind first a little. You need an object to represent a "line" - and make the colour a brush, not a string:
public class Line
{
public string LineNumber { get; set; }
public System.Windows.Media.Brush LineColour { get; set; }
}
Then you need code to build a collection of these which your ItemsControl can display. It might look something like this:
public partial class MainWindow : Window
{
private List<Line> _lines;
public MainWindow()
{
InitializeComponent();
_lines = new List<Line>();
// you can swap this for iterating around a database query or whatever you use to store the lines / calls
_lines.Add(new Line() { LineNumber = "line1", LineColour = new SolidColorBrush(Colors.Red) });
_lines.Add(new Line() { LineNumber = "line2", LineColour = new SolidColorBrush(Colors.Green) });
_lines.Add(new Line() { LineNumber = "line3", LineColour = new SolidColorBrush(Color.FromRgb(255, 188, 59)) });
// this part binds this list to your itemsControl
items.ItemsSource = _lines;
}
Then your XAML is fairly easy, you just define an ItemsControl called "items" and define a style which will be applied to each item. This will contain the line number apply the brush to the image, which you will make a "Path":
<!-- this bit defines how each item looks-->
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="60"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Path Grid.Column="0" Fill="{Binding LineColour}" Data="F1M52.5221,11.1016C52.0637,10.6796 44.4973,4.55737 29.4347,12.7369 26.3098,14.4296 23,17.224 20.095,20.1692 17.1497,23.073 14.3555,26.3842 12.6626,29.509 4.48303,44.5703 10.6093,52.1393 11.0298,52.5962 11.0298,52.5962 12.9778,55.5885 14.7057,53.8579L23.3555,45.2134C24.897,43.6692 22.7721,39.2134 18.2563,39.3541 17.1301,39.3906 15.5481,38.9531 17.0571,35.5156 18.3945,32.4623 22.3436,27.4766 24.8879,24.9648 27.4048,22.418 32.3904,18.4713 35.4426,17.1301 38.8787,15.6223 39.3175,17.2031 39.2811,18.332 39.1393,22.8462 43.5962,24.9686 45.1366,23.4283L53.7864,14.7787C55.5142,13.052,52.5221,11.1016,52.5221,11.1016z"/>
<TextBlock Grid.Column="1" Text="{Binding LineNumber}"/>
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
<!-- this bit defines the list appearance, we'll go vertical in a stack panel! -->
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
If you are using MVVM, everything still applies, but instead of assigning the ItemsSource in code behind, you would bind to the _lines collection of your view model - and you would make that an ObservableCollection rather than List if you wanted to add/remove dynamically.
But I have given you the simplest case as that's what your original question suggests!

Binding on dynamically-added elements

TPTB have decided that our app must run in a single window, popping up new windows in modal mode is not allowed.
And naturally, we have a UI design that involves popping up modal dialogs all over the place.
So I added a top-level Grid to the Window. In that Grid I defined no rows or columns, so everything draws in Row 0/Column 0.
The first element in the Grid was another Grid that contained everything that was normally displayed in the Window. The second was a full-sized Border with a gray, semi-transparent Background. The rest were Borders with wide Margins and white Backgrounds, containing the various UserControls that needed to be displayed as popups. All but the first had Visibility="Collapsed".
And then, when I needed to show a popup, I'd set Visibility="Visible" on the gray background and on the appropriate UserControl. The result was a nice shadowbox effect that worked fine.
Until somebody decided that the popups needed to be able to display popups. In a non-predictable order.
The limitation of the method I had implemented, using Visibility="Collapsed" elements in a Grid was that their order was fixed. UserControlB would always be displayed on top of UserControlA, even if it was UserControlB that asked to have UserControlA displayed. And that's not acceptable.
So my next attempt was to define the various UserControls in Window.Resources, and to add them to the Grid in code:
this.masterGrid.Children.Add(this.Resources["userControlA"] as UserControlA);
And that almost works. But the bindings are all messed up.
As an example, one of the controls is supposed to bind a Property to the CurrentItem of a collection in a member object of the Window's viewmodel. When I had the control defined as an invisible item in the Grid, it worked fine. But when I defined it as a Resource, the Property was null - it was never bound.
So I tried binding it in code, after I added it to the grid:
userControlA.SetBinding(UserControlA.myProperty, new Binding()
{ Source = this.viewModel.myCollection.CurrentItem });
And that compiles and runs just fine, but I'm not binding to the right object.
The first time I display the UserControl, I see the right object bound to it. But when I close it, and move the CurrentItem in the collection to a different object, and display the UserControl again, I still see the first object bound. If I close it again, and open it a third time, then I will see the right object bound to the control.
I've checked in code, and the CurrentItem that I'm binding to is right, every time, but it only seems to take every other time.
So I tried explicitly clearing the binding, first:
BindingOperations.ClearBinding(userControlA, UserControlA.myProperty);
userControlA.SetBinding(UserControlA.myProperty, new Binding()
{ Source = this.viewModel.myCollection.CurrentItem });
But that doesn't seem to have made any difference.
In all, it feels like I'm running down a rabbit hole, chasing deeper and deeper into complexity, to solve what should be a fairly simple problem.
Does anyone have any suggestions as to:
How to get binding to work on dynamically-added elements, or
How to get arbitrarily-ordered popups to display, as shadowboxes, without using dynamically-ordered elements?
Thanks in advance.
While it seems really odd for me that you can't create new Windows, I would definitely recommend not to complicate it too much by doing unnecesary things such as storing your views in the MainWindow's resources.
It would be better if you just added new instances of these elements into an ObservableCollection:
XAML:
<Window x:Class="WpfApplication4.Window8"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4"
Title="Window8" Height="300" Width="300">
<Window.Resources>
<DataTemplate DataType="{x:Type local:ViewModel1}">
<StackPanel Background="Green">
<TextBlock Text="This is ViewModel1!!"/>
<TextBlock Text="{Binding Text}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel2}">
<StackPanel Background="Blue" HorizontalAlignment="Center">
<TextBlock Text="This is ViewModel2!!"/>
<TextBlock Text="{Binding Text2}"/>
</StackPanel>
</DataTemplate>
<DataTemplate DataType="{x:Type local:ViewModel3}">
<StackPanel Background="Red" VerticalAlignment="Center">
<TextBlock Text="This is ViewModel3!!"/>
<TextBlock Text="{Binding Text3}"/>
<TextBox Text="{Binding Text3}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>
<DockPanel>
<Button Width="100" Content="Add" Click="Add_Click" DockPanel.Dock="Top"/>
<Button Width="100" Content="Remove" Click="Remove_Click" DockPanel.Dock="Top"/>
<ListBox ItemsSource="{Binding ActiveWidgets}" SelectedItem="{Binding SelectedWidget}">
<ListBox.Template>
<ControlTemplate>
<ItemsPresenter/>
</ControlTemplate>
</ListBox.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<ContentPresenter ContentSource="Content"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</DockPanel>
</Window>
Code Behind:
using System.Linq;
using System.Windows;
using System.Collections.ObjectModel;
using System;
namespace WpfApplication4
{
public partial class Window8 : Window
{
private WidgetsViewModel Widgets { get; set; }
public Window8()
{
InitializeComponent();
DataContext = Widgets = new WidgetsViewModel();
}
private Random rnd = new Random();
private int lastrandom;
private void Add_Click(object sender, RoutedEventArgs e)
{
var random = rnd.Next(1, 4);
while (random == lastrandom)
{
random = rnd.Next(1, 4);
}
lastrandom = random;
switch (random)
{
case 1:
Widgets.ActiveWidgets.Add(new ViewModel1() {Text = "This is a Text"});
break;
case 2:
Widgets.ActiveWidgets.Add(new ViewModel2() { Text2 = "This is another Text" });
break;
case 3:
Widgets.ActiveWidgets.Add(new ViewModel3() { Text3 = "This is yet another Text" });
break;
}
Widgets.SelectedWidget = Widgets.ActiveWidgets.LastOrDefault();
}
private void Remove_Click(object sender, RoutedEventArgs e)
{
Widgets.ActiveWidgets.Remove(Widgets.SelectedWidget);
Widgets.SelectedWidget = Widgets.ActiveWidgets.LastOrDefault();
}
}
public class WidgetsViewModel: ViewModelBase
{
public ObservableCollection<ViewModelBase> ActiveWidgets { get; set; }
private ViewModelBase _selectedWidget;
public ViewModelBase SelectedWidget
{
get { return _selectedWidget; }
set
{
_selectedWidget = value;
NotifyPropertyChange(() => SelectedWidget);
}
}
public WidgetsViewModel()
{
ActiveWidgets = new ObservableCollection<ViewModelBase>();
}
}
public class ViewModel1: ViewModelBase
{
public string Text { get; set; }
}
public class ViewModel2: ViewModelBase
{
public string Text2 { get; set; }
}
public class ViewModel3: ViewModelBase
{
public string Text3 { get; set; }
}
}
Just copy and paste my code in a File - New - WPF Application and see the results for yourself.
Since the Grid always places the last UI Element added to it topmost, you will see that Adding items to the observablecollection makes these "different widgets" always appear on top of each other, with the topmost being the last one added.
The bottom line is, when WidgetA requests to open WidgetB, just create a new WidgetBViewModel and add it to the ActiveWidgets collection. Then, when WidgetB is no longer needed, just remove it.
Then, it's just a matter of putting your UserControls inside a proper DataTemplate for each ViewModel. I strongly suggest you keep a separate ViewModel for each of your Widgets, and if you need to share data between them, just share data between the ViewModels.
Don't attempt to do things like ListBox ItemsSource="{Binding Whatever, RelativeSource={RelativeSource FindAncestor, AncestorType=Window}" unless you have a good reason to.
This way you no longer have to deal with Panel.ZIndex stuff. Maybe you can create a couple of attached properties to deal with things like focus and whatnot, but this approach is dead simple, and by far more performant than the Visibility and the Resources approaches.

How to build a grid of controls in XAML?

I am trying to build a UI in WPF to a specification. The UI is for editing a collection of items. Each item has an editable string property, and also a variable number of read-only strings which the UI needs to display. It might look something like this:
or, depending on data, might have a different number of text label columns:
The number of text columns is completely variable and can vary from one to "lots". The specification calls for the columns to be sized to fit the longest entry (they are invariably very short), and the whole thing should look like a grid. This grid will be contained in a window, stretching the text box horizontally to fit the window.
Importantly, the text boxes can contain multi-line text and will grow automatically to fit the text. The rows below need to be pushed out of the way if that happens.
Question: what would be a good way of doing this in WPF?
Coming from a WinForms background, I am thinking of a TableLayoutPanel, which gets populated directly by code I write. However, I need to do this in WPF. While I could still just get myself a Grid and populate it in code, I would really rather prefer a way that's more in line with how things are done in WPF: namely, define a ViewModel, populate it, and then describe the View entirely in XAML. However, I can't think of a way of describing such a view in XAML.
The closest I can get to this using MVVM and XAML is to use an ItemsControl with one item per row, and use a data template which, in turn, uses another ItemsControl (stacked horizontally this time) for the variable number of labels, followed by the text box. Unfortunately, this can't be made to align vertically in a grid pattern like the spec requires.
This does not map all too well, you could probably use a DataGrid and retemplate it to look like this. In other approaches you may need to imperatively add columns or the like to get the layout done right.
(You can hook into AutoGeneratingColumn to set the width of that one writeable column to *)
You can create your own Panel and then decide on how you want the layout logic to work for the children that are put inside it.
Look at this for inspiration:
http://www.nbdtech.com/Blog/archive/2010/07/27/easy-form-layout-in-wpf-part-1-ndash-introducing-formpanel.aspx
You could have a "ColumnCount" property, and then use that within the MeassureOverride and ArrangeOverride to decide when to wrap a child.
Or you could modify this bit of code (I know it's Silverlight code, but it should be close to the same in WPF).
http://blogs.planetsoftware.com.au/paul/archive/2010/04/30/autogrid-ndash-part-1.aspx
Instead of having the same width for all columns (the default is 1-star "*"), you could add a List/Collection property that records the different column widths sized you want, then in the AutoGrid_LayoutUpdated use those widths to make the ColumnDefinition values.
You've asked for quite a bit, the following code shows how to build a grid with the controls you want that sizes as needed, along with setting up the bindings:
public void BuildListTemplate(IEnumerable<Class1> myData, int numLabelCols)
{
var myGrid = new Grid();
for (int i = 0; i < myData.Count(); i++)
{
myGrid.RowDefinitions.Add(new RowDefinition() { Height= new GridLength(0, GridUnitType.Auto)});
}
for (int i = 0; i < numLabelCols; i++)
{
myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(0, GridUnitType.Auto) });
}
myGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
for (int i = 0; i < myData.Count(); i++)
{
for (int j = 0; j < numLabelCols; j++)
{
var tb = new TextBlock();
tb.SetBinding(TextBlock.TextProperty, new Binding("[" + i + "].labels[" + j + "]"));
tb.SetValue(Grid.RowProperty, i);
tb.SetValue(Grid.ColumnProperty, j);
tb.Margin = new Thickness(0, 0, 20, 0);
myGrid.Children.Add(tb);
}
var edit = new TextBox();
edit.SetBinding(TextBox.TextProperty, new Binding("[" + i + "].MyEditString"));
edit.SetValue(Grid.RowProperty, i);
edit.SetValue(Grid.ColumnProperty, numLabelCols);
edit.AcceptsReturn = true;
edit.TextWrapping = TextWrapping.Wrap;
edit.Margin = new Thickness(0, 0, 20, 6);
myGrid.Children.Add(edit);
}
contentPresenter1.Content = myGrid;
}
A Quick Explanation of the above All it is doing is creating the grid, defines rows for the grid; and a series of columns for the grid that auto size for the content.
Then it simply generates controls for each data point, sets the binding path, and assigns various other display attributes along with setting the correct row/column for the control.
Finally it puts the grid in a contentPresenter that has been defined in the window xaml in order to show it.
Now all you need do is create a class with the following properties and set the data context of the contentPresenter1 to a list of that object:
public class Class1
{
public string[] labels { get; set; }
public string MyEditString { get; set; }
}
just for completeness here is the window xaml and constructor to show hooking it all up:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<ContentPresenter Name="contentPresenter1"></ContentPresenter>
</Window>
public MainWindow()
{
InitializeComponent();
var data = new List<Class1>();
data.Add(new Class1() { labels = new string[] {"the first", "the second", "the third"}, MyEditString = "starting text"});
data.Add(new Class1() { labels = new string[] { "col a", "col b" }, MyEditString = "<Nothing>" });
BuildListTemplate(data, 3);
DataContext = data;
}
You can of course use other methods such as a listview and build a gridview for it (I'd do this if you have large numbers of rows), or some other such control, but given your specific layout requirements probably you are going to want this method with a grid.
EDIT: Just spotted that you're looking for a way of doing in xaml - tbh all I can say is that I don't think that with the features you're wanting that it is too viable. If you didn't need to keep things aligned to dynamically sized content on seperate rows it would be more viable... But I will also say, don't fear code behind, it has it's place when creating the ui.
Doing it in the code-behind is really not a WPFish(wpf way).
Here I offer you my solution, which looks nice imo.
0) Before starting, you need GridHelpers. Those make sure you can have dynamically changing rows/columns. You can find it with a little bit of google:
How can I dynamically add a RowDefinition to a Grid in an ItemsPanelTemplate?
Before actually implementing something, you need to restructure your program a little. You need new structure "CustomCollection", which will have:
RowCount - how many rows are there(implement using INotifyPropertyChanged)
ColumnCount - how many columns are there(implement using INotifyPropertyChanged)
ActualItems - Your own collection of "rows/items"(ObservableCollection)
1) Start by creating an ItemsControl that holds Grid. Make sure Grid RowDefinitions/ColumnDefinitions are dynamic. Apply ItemContainerStyle.
<ItemsControl
ItemsSource="{Binding Collection.ActualItems,
Converter={StaticResource presentationConverter}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid
local:GridHelpers.RowCount="{Binding Collection.RowCount}"
local:GridHelpers.StarColumns="{Binding Collection.ColumnCount,
Converter={StaticResource subtractOneConverter}"
local:GridHelpers.ColumnCount="{Binding Collection.ColumnCount}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Grid.Row" Value="{Binding RowIndex}"/>
<Setter Property="Grid.Column" Value="{Binding ColumnIndex}"/>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
The only thing left to do: implement presentationConverter which converts your Viewmodel presentation to View presentation. (Read: http://wpftutorial.net/ValueConverters.html)
The converter should give back a collection of items where each "label" or "textbox" is a seperate entity. Each entity should have RowIndex and ColumnIndex.
Here is entity class:
public class SingleEntity
{
..RowIndex property..
..ColumnIndex property..
..ContentProperty.. <-- This will either hold label string or TextBox binded property.
..ContentType..
}
Note that ContentType is an enum which you will bind against in ItemsTemplate to decide if you should create TextBox or Label.
This might seem like a quite lengthy solution, but it actually is nice for few reasons:
The ViewModel does not have any idea what is going on. This is purely View problem.
Everything is dynamic. As soon you add/or remove something in ViewModel(assuming everything is properly implemented), your ItemsControl will retrigger the Converter and bind again. If this is not the case, you can set ActualItems=null and then back.
If you have any questions, let me know.
Well, the simple yet not not very advanced way would be to fill the UI dynamically in the code-behind. This seems to be the easiest solution, and it more or less matches your winforms experience.
If you want to do it in a MVVM way, you should perhaps use ItemsControl, set the collection of items as its ItemsSource, and define a DataTemplate for your collection item type.
I would have the DataTemplate with something like that:
<Window x:Class="SharedSG.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:app="clr-namespace:SharedSG"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type app:LabelVM}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="G1"/>
<ColumnDefinition SharedSizeGroup="G2"/>
<ColumnDefinition MinWidth="40" Width="*"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding L1}" Grid.Column="0"/>
<Label Content="{Binding L2}" Grid.Column="1"/>
<TextBox Grid.Column="2"/>
</Grid>
</DataTemplate>
</Window.Resources>
<Grid Grid.IsSharedSizeScope="True">
<ItemsControl ItemsSource="{Binding}"/>
</Grid>
</Window>
You're probably way past this issue, but I had a similar issue recently and I got it to work surprisingly well in xaml, so I thought I'd share my solution.
The major downside is that you have to be willing to put an upper-bound on what "lots" of labels means. If lots can mean 100s, this won't work. If lots will definitely be less than the number of times you're willing to type Ctrl+V, you might be able to get this to work. You also have to be willing to put all the labels into a single ObservableCollection property in your view model. It sounded to me in your question that you already tried that out anyway though.
I takes advantage of AlternationIndex to get the index of the label and assign it to a column. Think I learned that from here. If an item has < x labels the extra columns won't get in the way. If an item has > x labels, the labels will start stacking on top of each other.
<!-- Increase AlternationCount and RowDefinitions if this template breaks -->
<ItemsControl ItemsSource="{Binding Labels}" IsTabStop="False" AlternationCount="5">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type ContentPresenter}">
<Setter Property="Grid.Column"
Value="{Binding RelativeSource={RelativeSource Self},
Path=(ItemsControl.AlternationIndex)}"/>
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid IsItemsHost="True">
<Grid.ColumnDefinitions>
<ColumnDefinition SharedSizeGroup="A"/>
<ColumnDefinition SharedSizeGroup="B"/>
<ColumnDefinition SharedSizeGroup="C"/>
<ColumnDefinition SharedSizeGroup="D"/>
<ColumnDefinition SharedSizeGroup="E"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>

Resources