First this is just for testing purposes
I have a xaml page that contains only a button and 2 stackpanels
The idea is to have a class, the class will have codes and names associated to it. the codes will be queried and based on the result a appropriate number of textboxes will display. I need to be able at the end of it add names to textboxes and save the list.
Here is my current code, it creates the textboxes the way I want it to but not too sure on saving of the list once they are filled in
xaml
<StackPanel x:Name="StackSG" Grid.Row="1" Grid.Column="0">
<ListBox ItemsSource="{Binding StackSG}" />
</StackPanel>
<StackPanel x:Name="StackSGName" Grid.Row="1" Grid.Column="1">
<ListBox ItemsSource="{Binding StackSGName}" />
</StackPanel>
<Button x:Name="Generate" Content="Generate" Height="23" Width="75" Grid.Row="0" Grid.Column="0"
Command="{Binding Path=GenerateSGKeys}"/>
</Grid>
</UserControl>
It connect to my viewmodel which looks like this
public class stackpnl : Notify
{
private IEnumerable stackSG;
public IEnumerable StackSG
{
get { return stackSG; }
set { stackSG = value; OnNotifyPropertyChanged("StackSG"); }
}
private IEnumerable stackSGName;
public IEnumerable StackSGName
{
get { return stackSGName; }
set { stackSGName = value; OnNotifyPropertyChanged("StackSGName"); }
}
private DelegateCommand generateSGKeys;
public ICommand GenerateSGKeys
{
get { return generateSGKeys; }
}
private IEnumerable allotments;
public IEnumerable Allotments
{
get { return allotments; }
set { allotments = value; OnNotifyPropertyChanged("Allotments"); }
}
TextBox txtSGName = new TextBox();
public stackpnl()
{
generateSGKeys = new DelegateCommand(Generate, OnGenerate);
StackSG = new List<TextBox>();
StackSGName = new List<TextBox>();
}
private bool OnGenerate(object obj)
{
return true;
}
public class Allotment
{
#region Properties
public string AllotmentName { get; set; }
public string AllotmentCode { get; set; }
#endregion
}
private void Generate(object obj)
{
IList<TextBox> StackSGTmp = new List<TextBox>();
IList<TextBox> StackSGNameTmp = new List<TextBox>();
IList<Allotment> newList = new List<Allotment>();
int st = 10;
for (int i = 0; i < st; i++)
{
newList.Add(new Allotment() { AllotmentCode = string.Format("{0}{1}", "Code", i.ToString()), AllotmentName = string.Format("{0}{1}", "Code", i.ToString()) });
}
foreach (var Allotment in newList)
{
TextBox txtSG = new TextBox();
txtSG.Name = string.Format(Allotment.AllotmentCode);
txtSG.Height = 25;
txtSG.Width = 75;
txtSG.Text = string.Format(Allotment.AllotmentCode);
txtSG.Visibility = System.Windows.Visibility.Visible;
StackSGTmp.Add(txtSG);
//Add SG name textboxes
txtSGName = new TextBox();
txtSGName.Name = string.Format(string.Format("{0}{1}", Allotment.AllotmentCode, Allotment.AllotmentName));
txtSGName.Height = 25;
txtSGName.Width = 75;
txtSGName.SetBinding(TextBox.TextProperty, new Binding(Allotment.AllotmentName) { Mode = BindingMode.TwoWay });
txtSGName.Visibility = System.Windows.Visibility.Visible;
txtSGName.KeyDown += new KeyEventHandler(txtSGName_KeyDown);
StackSGNameTmp.Add(txtSGName);
}
StackSG = StackSGTmp;
StackSGName = StackSGNameTmp;
}
void txtSGName_KeyDown(object sender, KeyEventArgs e)
{
BindingExpression binding = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
}
What you need to do is use the ItemTemplate of the ListBox to display the appropriate content. Your ListBox should not bind to a collection of TextBoxes, but instead bind to a collection of Allotments.
Update the xaml to
<ListBox ItemsSource="{Binding Allotments}" Grid.Row="1">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
<TextBox Text="{Binding AllotmentCode}"/>
<TextBox Text="{Binding AllotmentName}" Grid.Column="2"/>
</DataTemplate
</ListBox.ItemTemplate>
</ListBox>
Notice I removed the StackPanel you were using to wrap the ListBox as it is not needed. In your code you would then remove the StackSG, and StackSGName properties and populate your Allotments property within the Generate method.
Related
My scenario: I have a usercontrol consisting of a comboBox, and a TextBox. The comboBox should hold numbers contained in an ObservableCollection.
The task: The numbers in the ObservableCollection represent paths to book-chapters; therefore each chapter is unique. Meaning: if I have chapters 1 - 5, then the first userControl combo should show all chapters 1-5 (whereas one of them is selected randomly), the second userControl combo contains all chapters, but not the one selected in the previous combo, and so on. The textBox is for annotations for the chapters.
What I achieved so far: I have currently no model; just a main viewModel (ItemsViewModel in my case), and a viewModel for my userControl (PathViewModel). Then there is the mainWindow view.
The problem: On my mainWindow I can create several dynamically created userControls. The userControl TextBox is currently bound to a text property, while the index of the comboBox is bound to another property. But I don't know:
- how to gain access to the index, selected item/value of the specifically userControls
- how to react to a comboBox item/index change
Here is my code:
The userControl
<UserControl> <StackPanel Orientation="Horizontal">
<ComboBox x:Name="combo" Margin="10" MinWidth="60" VerticalAlignment="Center" ItemsSource="{Binding AvailableNumbers}" SelectedIndex="{Binding TheIndex}" />
<TextBox Margin="10" MinWidth="120" Text="{Binding TheText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</StackPanel>
The MainWindow
<Window>...<Window.DataContext>
<local:ItemsViewModel/>
</Window.DataContext>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel x:Name="HostPanel">
<ItemsControl ItemsSource="{Binding PathViewModels}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<local:PathControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
<StackPanel Grid.Column="1">
<Button Command="{Binding UCCreationCommand}" Content="Add User Control" Margin="10"/>
<Button Command="{Binding UCDeletionCommand}" CommandParameter="" Content="Delete User Control" Margin="10"/>
<Button Command="{Binding ReadoutCommand}" Content="Show ITEMS" Margin="10"/>
</StackPanel>
</Grid></Window>
My main ViewModel (called ItemsViewModel)
public class ItemsViewModel : NotifyPropertyChangedBase
{private int _aNumber;
public int ANumber
{
get { return _aNumber; }
set { _aNumber = value;
OnPropertyChanged(ref _aNumber, value);
}
}
public ObservableCollection<PathViewModel> PathViewModels { get; set; } = new
ObservableCollection<PathViewModel>();
public ObservableCollection<int> AllNumbers { get; set; } = new ObservableCollection<int>();
public ItemsViewModel()
{
UCCreationCommand = new CommandDelegateBase(UCCreationExecute, UCCreationCanExecute);
UCDeletionCommand = new CommandDelegateBase(UCDeletionExecute, UCDeletionCanExecute);
ReadoutCommand = new CommandDelegateBase(ReadoutExecute, ReadoutCanExecute);
AllNumbers.Add(1);
AllNumbers.Add(2);
AllNumbers.Add(3);
AllNumbers.Add(4);
AllNumbers.Add(5);
}
private bool ReadoutCanExecute(object paramerter)
{
if (PathViewModels.Count > 0)
{
return true;
}
return false;
}
private void ReadoutExecute(object parameter)
{
//just for testing
}
public ICommand UCCreationCommand { get; set; }
public ICommand UCDeletionCommand { get; set; }
public ICommand ReadoutCommand { get; set; }
private bool UCCreationCanExecute(object paramerter)
{
if (PathViewModels.Count < 8)
{
return true;
}
else
{
return false;
}
}
private void UCCreationExecute(object parameter)
{
PathViewModel p = new PathViewModel();
foreach (int i in AllNumbers)
{
p.AvailableNumbers.Add(i);
}
int rndIndex = 0;
Random rnd = new Random();
//creates a random chapter index
rndIndex = rnd.Next(0, p.AvailableNumbers.Count);
//just explicit for debugging reasons
p.TheIndex = rndIndex;
AllNumbers.RemoveAt(rndIndex);
PathViewModels.Add(p);
}
private bool UCDeletionCanExecute(object paramerter)
{
if (PathViewModels.Count != 0)
{
return true;
}
else
{
return false;
}
}
private void UCDeletionExecute(object parameter)
{
PathViewModel p = new PathViewModel();
int delIndex = PathViewModels.Count - 1;
p = PathViewModels[delIndex];
AllNumbers.Add((int)p.TheValue+1);
PathViewModels.Remove(p);
}
}
And finally my UserControl ViewModel:
public class PathViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<int> AvailableNumbers { get; set; } = new ObservableCollection<int>();
private int _theIndex;
public int TheIndex
{
get { return _theIndex; }
set
{
_theIndex = value;
OnPropertyChanged(ref _theIndex, value);
}
}
private int _theValue;
public int TheValue
{
get { return _theValue; }
set
{
_theValue = value;
OnPropertyChanged(ref _theValue, value);
}
}
private string _theText;
public string TheText
{
get { return _theText; }
set
{
_theText = value;
OnPropertyChanged(ref _theText, value);
}
}
public PathViewModel()
{
}
}
Any hints on how to go on from here would be highly appreaciated.
Has anyone tried filtering lists of controls? I have some simple sample code that will illustrate an issue that I can't seem to get around. When filtering lists of text I have no issues but when I turn the list into an observable list of controls any filter I run effects the other filters. Here is some sample code that works
Code:
public partial class MainWindow : Window
{
public ObservableCollection<string> testOC { get; set; }
public MainWindow()
{
InitializeComponent();
testOC = new ObservableCollection<string>();
for (int i = 0; i < 20; i++)
{
testOC.Add("Test Stuff " + i);
}
ListCollectionView view1 = new ListCollectionView(testOC);
ListCollectionView view2 = new ListCollectionView(testOC);
view1.Filter = Filter1;
view2.Filter = Filter2;
leftGrid.ItemsSource = testOC;
MiddleGrid.ItemsSource = view1;
rightGrid.ItemsSource = view2;
}
private bool Filter1(object test)
{
try
{
var testStuff = test as string;
if (testStuff.Contains("1"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
private bool Filter2(object test)
{
try
{
var testStuff = test as string;
if (testStuff.Contains("2"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
}
XML:
<Window x:Class="testTheFilter.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:testTheFilter"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="775"/>
</Grid.RowDefinitions>
<ItemsControl Name="leftGrid" Grid.Column="0" Grid.RowSpan="2"/>
<ItemsControl Name="MiddleGrid" Grid.Column="1" Grid.RowSpan="2"/>
<ItemsControl Name="rightGrid" Grid.Column="2" Grid.RowSpan="2"/>
</Grid>
Screenshot of code working:
This works as it should, you get three lists the first list contains all strings, the second contains only strings with 1's, and the third list contains only strings with 2's.
Now if I take that exact same code and change it to a list of controls it gets wonky
Here is code part:
public partial class MainWindow : Window
{
public ObservableCollection<Button> testOC { get; set; }
public MainWindow()
{
InitializeComponent();
testOC = new ObservableCollection<Button>();
for (int i = 0; i < 20; i++)
{
Button btn = new Button();
btn.Content = "Test Stuff " + i;
testOC.Add(btn);
}
ListCollectionView view1 = new ListCollectionView(testOC);
ListCollectionView view2 = new ListCollectionView(testOC);
view1.Filter = Filter1;
view2.Filter = Filter2;
leftGrid.ItemsSource = testOC;
MiddleGrid.ItemsSource = view1;
rightGrid.ItemsSource = view2;
}
private bool Filter1(object test)
{
try
{
var testStuff = test as Button;
if (testStuff.Content.ToString().Contains("1"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
private bool Filter2(object test)
{
try
{
var testStuff = test as Button;
if (testStuff.Content.ToString().Contains("2"))
{
return true;
}
return false;
}
catch (Exception)
{
throw;
}
}
}
Here is a screenshot of code not working:
Has anyone seen this behavior before and does anyone know how to fix this? I've spent hours researching this and can't seem to find a fix.
Thanks in advance
As you can't add one visual element (Button) to different parents at the same time, why not use DataTemplates? If you keep the code from your frist example, just edit the XAML and you're ready to go:
<Grid>
<Grid.Resources>
<DataTemplate x:Key="itemTemplate">
<Button>
<ContentPresenter Content="{Binding}" />
</Button>
</DataTemplate>
</Grid.Resources>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
<ColumnDefinition Width="150"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"/>
<RowDefinition Height="775"/>
</Grid.RowDefinitions>
<ItemsControl Name="leftGrid" Grid.Column="0" Grid.RowSpan="2" ItemTemplate="{StaticResource itemTemplate}" />
<ItemsControl Name="MiddleGrid" Grid.Column="1" Grid.RowSpan="2" ItemTemplate="{StaticResource itemTemplate}" />
<ItemsControl Name="rightGrid" Grid.Column="2" Grid.RowSpan="2" ItemTemplate="{StaticResource itemTemplate}" />
</Grid>
Like icebat said, one visual element can't be a child to several parents. Button is a visual element - string is not. If you change your code to this, you get the disired result:
public ObservableCollection<Button> testOC { get; set; }
public ObservableCollection<Button> testOC1 { get; set; }
public ObservableCollection<Button> testOC2 { get; set; }
public MainWindow()
{
InitializeComponent();
testOC = new ObservableCollection<Button>();
testOC1 = new ObservableCollection<Button>();
testOC2 = new ObservableCollection<Button>();
for (int i = 0; i < 20; i++)
{
var content = "Test Stuff " + i;
Button btn = new Button();
btn.Content = content;
testOC.Add(btn);
Button btn1 = new Button();
btn1.Content = content;
testOC1.Add(btn1);
Button btn2 = new Button();
btn2.Content = content;
testOC2.Add(btn2);
}
ListCollectionView view1 = new ListCollectionView(testOC1);
ListCollectionView view2 = new ListCollectionView(testOC2);
view1.Filter = Filter1;
view2.Filter = Filter2;
leftGrid.ItemsSource = testOC;
MiddleGrid.ItemsSource = view1;
rightGrid.ItemsSource = view2;
}
I've got this code. I need to have access to the ScheduleList from my c# code. But it's inaccessible. I can get access to SchedulePivot only.
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="0,0,0,50">
<Pivot x:Name="SchedulePivot" Margin="10,10,10,0" Title="Pivot" VerticalAlignment="Top">
<Pivot.ItemTemplate>
<DataTemplate>
<ListBox x:Name="ScheduleList" Margin="0,0,0,17" Width="Auto">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="52" Width="auto">
Searching on StackOverflow I have found this code:
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
return child;
}
else
{
// Not found it - search children
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
I use this line to get the child:
ListBox listCont = FindChildControl<ListBox>(this, "ScheduleList") as ListBox;
Also I tried doing like this:
ListBox listCont = FindChildControl<ListBox>(SchedulePivot, "ScheduleList") as ListBox;
than I do this:
listCont.Items.Add(items);
And get the exeption as listCont=null. What's wrong I'm doing?
I have tested your code, both of the following code work well in my side and I can get the correct result:
ListBox listCont = FindChildControl<ListBox>(this, "ScheduleList") as ListBox;
ListBox listCont = FindChildControl<ListBox>(SchedulePivot, "ScheduleList") as ListBox;
If we want to access the control by using the VisualTreeHelper, we should make sure that we have not called the above code inside the constructor of the MainPage, or we will get the null result as below. Because the control does not been initialized completely:
In order to get the correct result, we need to call the above code inside the MainPage.Loaded event or Button click event to make sure that control has been initialized completely, after that it should work fine.
The following is my sample, please try to refer to:
In the MainPage.xaml:
<Pivot x:Name="SchedulePivot" ItemsSource="{Binding PivotTestlist}" Margin="10,10,10,0" Title="Pivot" VerticalAlignment="Top">
<Pivot.HeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding header}"></TextBlock>
</DataTemplate>
</Pivot.HeaderTemplate>
<Pivot.ItemTemplate>
<DataTemplate>
<ListBox x:Name="ScheduleList" Margin="0,0,0,17" Width="Auto" ItemsSource="{Binding ListBoxTestlist}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Height="52" Width="auto">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding id}"></TextBlock>
<TextBlock Text="{Binding name}"></TextBlock>
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</Pivot.ItemTemplate>
</Pivot>
<Button Click="Button_Click" Content="Button"></Button>
In the MainPage.xaml.cs:
public class ListBoxTest
{
public string name { get; set; }
public string id { get; set; }
}
public class PivotTest
{
public List<ListBoxTest> ListBoxTestlist { get; set; }
public string header { get; set; }
}
public sealed partial class MainPage : Page
{
public List<PivotTest> PivotTestlist { get; set; }
public MainPage()
{
this.InitializeComponent();
PivotTestlist = new List<PivotTest>();
PivotTest PivotTest1 = new PivotTest();
PivotTest1.ListBoxTestlist = new List<ListBoxTest>();
PivotTest1.ListBoxTestlist.Add(new ListBoxTest() { name = "name1", id = "id1" });
PivotTest1.ListBoxTestlist.Add(new ListBoxTest() { name = "name2", id = "id2" });
PivotTest1.header = "header1";
PivotTestlist.Add(PivotTest1);
PivotTest PivotTest2 = new PivotTest();
PivotTest2.ListBoxTestlist = new List<ListBoxTest>();
PivotTest2.ListBoxTestlist.Add(new ListBoxTest() { name = "name11", id = "id11" });
PivotTest2.ListBoxTestlist.Add(new ListBoxTest() { name = "name22", id = "id22" });
PivotTest2.header = "header2";
PivotTestlist.Add(PivotTest2);
this.DataContext = this;
}
private DependencyObject FindChildControl<T>(DependencyObject control, string ctrlName)
{
int childNumber = VisualTreeHelper.GetChildrenCount(control);
for (int i = 0; i < childNumber; i++)
{
DependencyObject child = VisualTreeHelper.GetChild(control, i);
FrameworkElement fe = child as FrameworkElement;
// Not a framework element or is null
if (fe == null) return null;
if (child is T && fe.Name == ctrlName)
{
// Found the control so return
return child;
}
else
{
// Not found it - search children
DependencyObject nextLevel = FindChildControl<T>(child, ctrlName);
if (nextLevel != null)
return nextLevel;
}
}
return null;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ListBox listCont = FindChildControl<ListBox>(SchedulePivot, "ScheduleList") as ListBox;
int count = listCont.Items.Count;
}
}
The result:
Declare the Pivot in a storyboard and use the x:Key instead of x:Name.
e.g.
<StoryBoard>
<Pivot x:key="nameIt"/>
</StoryBoard>
private void AccesPivot ()
{ //now you can acces your pivot
}
I created a new TextBlock class which has ItemsSource property and translates that ItemsSource into "Run" object:
public class MultiTypeDynamicTextBlock : TextBlock
{
public interface ISection
{
Inline GetDisplayElement();
}
public class TextOption : ISection
{
private Run mText;
public TextOption(string aText)
{
mText = new Run();
mText.Text = aText.Replace("\\n", "\n");
}
public Inline GetDisplayElement()
{
return mText;
}
}
public class LineBreakOption : ISection
{
public Inline GetDisplayElement()
{
return new LineBreak();
}
public ISection Clone()
{
return new LineBreakOption();
}
}
public class ImageOption : ISection
{
private InlineUIContainer mContainer;
public ImageOption(string aDisplay)
{
Image lImage;
lImage = new Image();
lImage.Source = new BitmapImage(new Uri(Environment.CurrentDirectory + aDisplay));
lImage.Height = 15;
lImage.Width = 15;
mContainer = new InlineUIContainer(lImage);
}
public Inline GetDisplayElement()
{
return mContainer;
}
}
public static readonly DependencyProperty ItemsSourceProperty =
DependencyProperty.Register("ItemsSource", typeof(ObservableCollection<ISection>), typeof(MultiTypeDynamicTextBlock),
new UIPropertyMetadata(new ObservableCollection<ISection>(),
new PropertyChangedCallback(SetContent)));
public ObservableCollection<ISection> ItemsSource
{
get
{
return GetValue(ItemsSourceProperty) as ObservableCollection<ISection>;
}
set
{
if (ItemsSource != null)
ItemsSource.CollectionChanged -= CollectionChanged;
SetValue(ItemsSourceProperty, value);
SetContent();
ItemsSource.CollectionChanged += CollectionChanged;
}
}
private void CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
SetContent();
}
private static void SetContent(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DependencyObject lParent = d;
MultiTypeDynamicTextBlock lPanel = lParent as MultiTypeDynamicTextBlock;
if (lPanel != null)
{
lPanel.ItemsSource = e.NewValue as ObservableCollection<ISection>;
}
}
private void SetContent()
{
if (ItemsSource != null)
{
Inlines.Clear();
foreach (ISection lCurr in ItemsSource)
{
Inlines.Add(lCurr.GetDisplayElement());
}
}
}
If I Bind the ItemsSource directly to the DataContext, it works.
But if I bind it to an object that changes at runtime (such as SelectedItem on a ListBox) it doesn't update the text when a new item is selected.
<StackPanel>
<ListBox x:Name="TheList" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding ElementName=TheList, Path=SelectedItem}">
<TextBlock Text="{Binding Title}" FontSize="20"/>
<local:MultiTypeDynamicTextBlock ItemsSource="{Binding Items}"/>
</StackPanel>
</StackPanel>
Any reason why?
In your example, does the SelectedItem has two properties Title and Items? Or is Items a property in your viewmodel? If the answer is the latter, than you can find a solution below.
I don't entirely understand what you mean, but I'll give it a try.
If you mean that the ItemsSource on your custom control isn't set, than you have to point XAML into the right direction.
Below you can find a solution, if this is what you want to achieve.
What I did is pointing the compiler to the right source with this line of code:
ItemsSource="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType=Window}}"
Here you say that the compiler can find the Binding property in the DataContext of the Window (or any control where you can find the property).
<StackPanel>
<ListBox x:Name="TheList" ItemsSource="{Binding Items}" SelectedItem="{Binding SelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Title}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding ElementName=TheList, Path=SelectedItem}">
<TextBlock Text="{Binding Title}" FontSize="20"/>
<local:MultiTypeDynamicTextBlock ItemsSource="{Binding DataContext.Items, RelativeSource={RelativeSource AncestorType=Window}}"/>
</StackPanel>
</StackPanel>
Hopefully this helped.
EDIT
The title property will changes when I select another one from the ListBox.
If Items is set to a new ObservableCollection, do you call the OnPropertyChanged event for Items when the SelectedItem changes?
OnPropertyChanged("Items");
Thank you for your help.
I managed to fix this by updating the MultiTypeDynamicTextBlock as follows:
public class MultiTypeDynamicTextBlock : TextBlock
{
public interface ISection
{
Inline GetDisplayElement();
ISection Clone();
}
public class TextOption : ISection
{
private Run mText;
public TextOption(string aText)
{
mText = new Run();
mText.Text = aText.Replace("\\n", "\n");
}
public Inline GetDisplayElement()
{
return mText;
}
public ISection Clone()
{
return new TextOption(mText.Text);
}
}
public class LineBreakOption : ISection
{
public Inline GetDisplayElement()
{
return new LineBreak();
}
public ISection Clone()
{
return new LineBreakOption();
}
}
public class SectionList
{
private ObservableCollection<ISection> mList;
public Action CollectionChanged;
public ObservableCollection<ISection> Items
{
get
{
ObservableCollection<ISection> lRet = new ObservableCollection<ISection>();
foreach (ISection lCurr in mList)
{
lRet.Add(lCurr.Clone());
}
return lRet;
}
}
public int Count { get { return mList.Count; } }
public SectionList()
{
mList = new ObservableCollection<ISection>();
}
public void Add(ISection aValue)
{
mList.Add(aValue);
}
public SectionList Clone()
{
SectionList lRet = new SectionList();
lRet.mList = Items;
return lRet;
}
}
public MultiTypeDynamicTextBlock()
{
}
public static readonly DependencyProperty ItemsCollectionProperty =
DependencyProperty.Register("ItemsCollection", typeof(SectionList), typeof(MultiTypeDynamicTextBlock),
new UIPropertyMetadata((PropertyChangedCallback)((sender, args) =>
{
MultiTypeDynamicTextBlock textBlock = sender as MultiTypeDynamicTextBlock;
SectionList inlines = args.NewValue as SectionList;
if (textBlock != null)
{
if ((inlines != null) && (inlines.Count > 0))
{
textBlock.ItemsCollection.CollectionChanged += textBlock.ResetInlines;
textBlock.Inlines.Clear();
foreach (ISection lCurr in textBlock.ItemsCollection.Items)
{
textBlock.Inlines.Add(lCurr.GetDisplayElement());
}
}
else
{
inlines = new SectionList();
inlines.Add(new TextOption("No value set"));
textBlock.ItemsCollection = inlines;
}
}
})));
public SectionList ItemsCollection
{
get
{
return (SectionList)GetValue(ItemsCollectionProperty);
}
set
{
SectionList lTemp;
if (value == null)
{
lTemp = new SectionList();
lTemp.Add(new TextOption("No value set for property"));
}
else
{
lTemp = value;
}
SetValue(ItemsCollectionProperty, lTemp);
}
}
private void ResetInlines()
{
Inlines.Clear();
foreach (ISection lCurr in ItemsCollection.Items)
{
Inlines.Add(lCurr.GetDisplayElement());
}
}
}
And I update the fields that were Binded to be of type MultiTypeDynamicTextBlock.SectionList
As long as I am using a copy (Clone) it is working, for some reason when I don't clone it removes the value from the display in the list, if someone knows why I would love to learn but I managed to go around it.
the XAML of the window is:
<StackPanel>
<ListBox x:Name="TheList" ItemsSource="{Binding GeneralItems}" SelectedItem="{Binding SelectedItem}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Title}" FontSize="20"/>
<local:MultiTypeDynamicTextBlock ItemsCollection="{Binding Items}" Margin="20,0,0,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding GeneralItems, Path=SelectedItem}">
<TextBlock Text="{Binding Title}" FontSize="20"/>
<local:MultiTypeDynamicTextBlock DataContext="{Binding Items}" ItemsCollection="{Binding}" Margin="20,0,0,0"/>
</StackPanel>
</StackPanel>
Recently I started building my own big Windows 8 Store App.
Working on UI I started replicating some good UIs.
One I met very interesting animation of inserting new elements in list view in standard Mail app. When you click on chain it expands and shows all messages in chain.
Here is captured video.
I have no idea what technique did they use to achieve this animation and behavior.
Can anyone help me, explain or give example how can I achieve such behavior? Thanks.
The mail app is written in JavaScript, so it won't help you much to know how it was done since this UI stack is quite different than the XAML one. The thing though is that the list controls are likely animated the same way, so you only need to add/remove some items in the list to get the expansion/collapse effect.
I played with it for a bit and this is what I came up with that uses ListView's ItemTemplateSelector property to define a few different item templates.
<Page
x:Class="App82.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:App82"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<Page.Resources>
<local:CollapsibleListItemTemplateSelector
x:Key="collapsibleListItemTemplateSelector">
<local:CollapsibleListItemTemplateSelector.BasicItemTemplate>
<DataTemplate>
<Border
Margin="5"
Height="50"
VerticalAlignment="Stretch"
BorderBrush="ForestGreen"
BorderThickness="2,0,0,0">
<StackPanel
Margin="10,0,0,0">
<TextBlock
FontWeight="Bold"
Text="{Binding Title}" />
<TextBlock
Text="{Binding Gist}" />
</StackPanel>
</Border>
</DataTemplate>
</local:CollapsibleListItemTemplateSelector.BasicItemTemplate>
<local:CollapsibleListItemTemplateSelector.ExpandedItemTemplate>
<DataTemplate>
<Border
Margin="15,5,5,5"
Height="50"
VerticalAlignment="Stretch"
BorderBrush="Yellow"
BorderThickness="2,0,0,0">
<StackPanel
Margin="10,0,0,0">
<TextBlock
FontWeight="Bold"
Text="{Binding Title}" />
<TextBlock
Text="{Binding Gist}" />
</StackPanel>
</Border>
</DataTemplate>
</local:CollapsibleListItemTemplateSelector.ExpandedItemTemplate>
<local:CollapsibleListItemTemplateSelector.CollapsibleItemTemplate>
<DataTemplate>
<Border
Margin="5"
Height="50"
VerticalAlignment="Stretch"
BorderBrush="DodgerBlue"
BorderThickness="2,0,0,0">
<StackPanel
Margin="10,0,0,0"
Orientation="Horizontal">
<TextBlock
FontWeight="Bold"
Text="{Binding ChildItems.Count}" />
<TextBlock
FontWeight="Bold"
Text=" Items" />
</StackPanel>
</Border>
</DataTemplate>
</local:CollapsibleListItemTemplateSelector.CollapsibleItemTemplate>
</local:CollapsibleListItemTemplateSelector>
</Page.Resources>
<Grid
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<ListView
x:Name="ListView"
ItemTemplateSelector="{StaticResource collapsibleListItemTemplateSelector}"
ItemClick="OnItemClick"
IsItemClickEnabled="True" />
</Grid>
</Page>
Code behind:
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using App82.Common;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
namespace App82
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var items = new ObservableCollection<BindableBase>();
var item1 = new BasicItem { Title = "Item 1", Gist = "This item has some content that is not fully shown..." };
var item2 = new ExpandedItem { Title = "Item 2", Gist = "This item has some content that is not fully shown..." };
var item3 = new ExpandedItem { Title = "Item 3", Gist = "This item has some content that is not fully shown..." };
var item4 = new ExpandedItem { Title = "Item 4", Gist = "This item has some content that is not fully shown..." };
var item5 = new BasicItem { Title = "Item 5", Gist = "This item has some content that is not fully shown..." };
var itemGroup1 = new CollapsibleItem(items, new[] { item2, item3, item4 });
items.Add(item1);
items.Add(itemGroup1);
items.Add(item5);
this.ListView.ItemsSource = items;
}
private void OnItemClick(object sender, ItemClickEventArgs e)
{
var collapsibleItem = e.ClickedItem as CollapsibleItem;
if (collapsibleItem != null)
collapsibleItem.ToggleCollapse();
}
}
public class CollapsibleListItemTemplateSelector : DataTemplateSelector
{
public DataTemplate BasicItemTemplate { get; set; }
public DataTemplate CollapsibleItemTemplate { get; set; }
public DataTemplate ExpandedItemTemplate { get; set; }
protected override Windows.UI.Xaml.DataTemplate SelectTemplateCore(object item, Windows.UI.Xaml.DependencyObject container)
{
if (item is ExpandedItem)
return ExpandedItemTemplate;
if (item is BasicItem)
return BasicItemTemplate;
//if (item is CollapsibleItem)
return CollapsibleItemTemplate;
}
}
public class BasicItem : BindableBase
{
#region Title
private string _title;
public string Title
{
get { return _title; }
set { this.SetProperty(ref _title, value); }
}
#endregion
#region Gist
private string _gist;
public string Gist
{
get { return _gist; }
set { this.SetProperty(ref _gist, value); }
}
#endregion
}
public class ExpandedItem : BasicItem
{
}
public class CollapsibleItem : BindableBase
{
private readonly IList _hostCollection;
#region IsExpanded
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set
{
if (this.SetProperty(ref _isExpanded, value))
{
if (_isExpanded)
Expand();
else
Collapse();
}
}
}
#endregion
#region ChildItems
private ObservableCollection<BasicItem> _childItems;
public ObservableCollection<BasicItem> ChildItems
{
get { return _childItems; }
set { this.SetProperty(ref _childItems, value); }
}
#endregion
public CollapsibleItem(
IList hostCollection,
IEnumerable<BasicItem> childItems)
{
_hostCollection = hostCollection;
_childItems = new ObservableCollection<BasicItem>(childItems);
}
public void ToggleCollapse()
{
IsExpanded = !IsExpanded;
}
private void Expand()
{
int i = _hostCollection.IndexOf(this) + 1;
foreach (var childItem in ChildItems)
{
_hostCollection.Insert(i++, childItem);
}
}
private void Collapse()
{
int i = _hostCollection.IndexOf(this) + 1;
for (int index = 0; index < ChildItems.Count; index++)
{
_hostCollection.RemoveAt(i);
}
}
}
}