Changing DataContext doesn't update list fields - c#

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>

Related

Get all selected items across multiple nested ListBoxes with SelectionMode Multiple/Extended

I have a List of Lists and display it with nested ListBoxes:
MainWindow.xaml.cs
using System.Collections.Generic;
namespace WPF_Sandbox
{
public partial class MainWindow
{
public IEnumerable<IEnumerable<string>> ListOfStringLists { get; set; } = new[] { new[] { "a", "b" }, new[] { "c", "d" } };
public MainWindow()
{
InitializeComponent();
DoSomethingButton.Click += (sender, e) =>
{
// do something with all selected items
};
}
}
}
MainWindow.xaml
<Window x:Class="WPF_Sandbox.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow"
x:Name="ThisControl">
<StackPanel>
<ListBox ItemsSource="{Binding ListOfStringLists, ElementName=ThisControl}">
<ListBox.ItemTemplate>
<ItemContainerTemplate>
<ListBox ItemsSource="{Binding}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<ItemContainerTemplate>
<TextBlock Text="{Binding}" />
</ItemContainerTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ItemContainerTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="DoSomethingButton" Content="DoSomething" />
</StackPanel>
</Window>
How can I get all selected items across all ListBoxes?
I found a few solutions getting one selected item but could not figure out how to do applie those in my scenario.
I have an idea on how to do this by wrapping the string arrays but I would prefer not doing this.
I would just add an event handler to the inner ListBox like so if not doing things the MVVM way:
<ListBox ItemsSource="{Binding}" SelectionMode="Multiple" SelectionChanged="ListBox_SelectionChanged">
Then in your code behind implement the ListBox_SelectionChanged like so:
public List<string> FlatStringList = new List<string>();
private void ListBox_SelectionChanged(object sender,System.Windows.Controls.SelectionChangedEventArgs e)
{
FlatStringList.AddRange(e.AddedItems.Cast<string>());
foreach(string s in e.RemovedItems)
{
FlatStringList.Remove(s);
}
}
This is assuming you don't mind storing the selected strings in a flat list. Then you could implement your DoSomething button click event handler to do something with the FlatStringList.
Hope that helps.
The easiest way would be to iterate through the items in the ListBoxes:
private void DoSomethingButton_Click(object sender, RoutedEventArgs e)
{
List<string> selectedStrings = new List<string>();
foreach (IEnumerable<string> array in outerListBox.Items.OfType<IEnumerable<string>>())
{
ListBoxItem lbi = outerListBox.ItemContainerGenerator.ContainerFromItem(array) as ListBoxItem;
if (lbi != null)
{
ListBox innerListBox = GetChildOfType<ListBox>(lbi);
if (innerListBox != null)
{
foreach (string selectedString in innerListBox.SelectedItems.OfType<string>())
selectedStrings.Add(selectedString);
}
}
}
}
private static T GetChildOfType<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj == null)
return null;
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
var child = VisualTreeHelper.GetChild(depObj, i);
var result = (child as T) ?? GetChildOfType<T>(child);
if (result != null)
return result;
}
return null;
}
Note that the ListBoxItem may be virtualized away if you have a lot of inner IEnumerable<string>. You will then have to force the generation of the containers or disable UI virtualization:
WPF ListView virtualization. How to disable ListView virtualization?
This may affect the performance negatively so if this is an issue you should probably consider binding to an IEnumerable<YourType> and bind the SelectedItems property of the inner ListBox to a property of a YourType using a behaviour.
Since the SelectedItems property of a ListBox is read-only you can't bind to it directly: https://blog.magnusmontin.net/2014/01/30/wpf-using-behaviours-to-bind-to-readonly-properties-in-mvvm/.
Why don't you create a wrapper (as you said):
public class MyString : INotifyPropertyChanged
{
public MyString(string value) { Value = value; }
string _value;
public string Value { get { return _value; } set { _value = value; RaisePropertyChanged("Value"); } }
bool _isSelected;
public bool IsSelected { get { return _isSelected; } set { _isSelected = value; RaisePropertyChanged("IsSelected"); } }
public event PropertyChangedEventHandler PropertyChanged;
void RaisePropertyChanged(string propname)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propname));
}
}
Bind the IsSelected property of the ListBoxItems:
<StackPanel>
<ListBox ItemsSource="{Binding ListOfStringLists, ElementName=ThisControl}">
<ListBox.ItemTemplate>
<ItemContainerTemplate>
<ListBox ItemsSource="{Binding}" SelectionMode="Multiple">
<ListBox.ItemTemplate>
<ItemContainerTemplate>
<TextBlock Text="{Binding Value}" />
</ItemContainerTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
</ItemContainerTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Name="DoSomethingButton" Content="DoSomething" />
</StackPanel>
and you are already done:
public IEnumerable<IEnumerable<MyString>> ListOfStringLists { get; set; } = new[] { new[] { new MyString("a"), new MyString("b") { IsSelected = true } }, new[] { new MyString("c"), new MyString("d") } };
public MainWindow()
{
this.InitializeComponent();
DoSomethingButton.Click += (sender, e) =>
{
foreach (var i in ListOfStringLists)
foreach (var j in i)
{
if (j.IsSelected)
{
// ....
}
}
};
}

ListView in Listview - SelectedIndex of parent not set when selecting child

I have a UI which displays a ListView in a ListView:
<ListView
SelectedIndex="{x:Bind ParentViewModel.SelectedParentIndex, Mode=TwoWay}"
ItemsSource="{x:Bind ParentViewModel.ParentViewModels, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="viewModels:ParentViewModel">
<StackPanel>
<TextBlock Text="{Binding ParentName}" />
<ListView
SelectedIndex="{x:Bind SelectedChildIndex, Mode=TwoWay}"
ItemsSource="{Binding ChildViewModels, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="viewModels:ChildViewModel">
<TextBlock Text="{Binding ChildName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
When I click on a parent element the SelectedParentIndex gets set and when I click on a child element the SelectedChildIndex gets set.
My problem is that when I click on a child element i don't know to wich parent element it belongs because the SelectedParentIndex is not set. How can I solve this?
And the flow how it should be:
Just add an event in. Here is a compiled working example.
<ListView
ItemsSource="{Binding ParentViewModels, Mode=OneWay}"
SelectedIndex="{Binding SelectedParentIndex, Mode=TwoWay}"
SelectedItem="{Binding SelectedParent,Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate >
<StackPanel>
<TextBlock Text="{Binding ParentName}" />
<ListView
ItemsSource="{Binding ChildViewModels, Mode=OneWay}"
SelectedIndex="{Binding SelectedChildIndex, Mode=TwoWay}"
SelectedItem="{Binding SelectedChild,Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding ChildName}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
Here are the cs files. Please pay close attention to the structure.
The MasterViewModel is your DataContext for your View. It handles the SelectedParent, the SelectedParentIndex and your parents collection.
public class MasterViewModel : ViewModelBase
{
private ParentViewModel _SelectedParent;
public ParentViewModel SelectedParent
{
get { return _SelectedParent; }
set
{
_SelectedParent = value;
OnPropertyChanged("SelectedParent");
}
}
private int _SelectedParentIndex;
public int SelectedParentIndex
{
get { return _SelectedParentIndex; }
set
{
_SelectedParentIndex = value;
OnPropertyChanged("SelectedParentIndex");
}
}
public ObservableCollection<ParentViewModel> ParentViewModels
{
get; private set;
}
public MasterViewModel()
{
ParentViewModels = new ObservableCollection<ParentViewModel>();
LoadData();
}
private void LoadData()
{
for(int x = 0; x < 10; x++)
{
ParentViewModel parent = new ParentViewModel();
parent.ChildChangedEvent += Parent_ChildChangedEvent;
for(int y = 0; y < 20; y++)
{
ChildViewModel child = new ChildViewModel()
{ ChildName = "Child " + y };
parent.ChildViewModels.Add(child);
}
ParentViewModels.Add(parent);
}
}
private void Parent_ChildChangedEvent(object sender, EventArgs e)
{
SelectedParent = (ParentViewModel)sender;
}
}
Your ParentViewModel contains your SelectedChildIndex, your SelectedChild and your ChildViewModels collection. It also has a name property
Notice that I added an EventHandler to your ParentViewModel. When the SelectedChild is updated, it fires the event off. Then, we handle this event in the MasterViewModel where we can force the SelectedParent to update.
public class ParentViewModel : ViewModelBase
{
public String ParentName { get; set; }
private int _SelectedChildIndex;
public int SelectedChildIndex
{
get { return _SelectedChildIndex; }
set
{
_SelectedChildIndex = value;
OnPropertyChanged("SelectedChildIndex");
}
}
private ChildViewModel _SelectedChild;
public ChildViewModel SelectedChild
{
get { return _SelectedChild; }
set
{
_SelectedChild = value;
OnPropertyChanged("SelectedChild");
if (ChildChangedEvent != null)
{
ChildChangedEvent(this, new EventArgs());
}
}
}
public ObservableCollection<ChildViewModel> ChildViewModels
{
get; private set;
}
public event EventHandler ChildChangedEvent;
public ParentViewModel()
{
ChildViewModels = new ObservableCollection<ChildViewModel>();
}
}
Your ChildViewModel just has a name property.
public class ChildViewModel : ViewModelBase
{
private string _childName;
public string ChildName
{
get { return _childName; }
set
{
_childName = value;
OnPropertyChanged("ChildName");
}
}
}
The ViewModelBase just updates the UI
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propName));
}
}
}

How to represent hierarchical DATA using HierarchicalDataTemplate in wpf

I am using MVVM and trying to represent my ViewModel data in View.
I have a class called Track containing list of Variations. I want to represent each variation as a TextBlock using data binding.
I am able to represent a single track as:
<Window.Resources>
<src:Track x:Key="trck"/>
...
</Window.Resources>
<StackPanel DataContext="{Binding Source={StaticResource trck}}" Orientation="Horizontal">
<ItemsControl ItemsSource="{Binding Vars}" Height="53" Width="349">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock Background="{Binding Path=color}" Height="15" Width="{Binding Path=elapsedtime}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
I also have a class called TrackList containing collection of Tracks.
I tried to use HierarchicalDataTemplate to represent Hierarchical Data of TrackList.
But it's not working..
I am new to WPF, and I have tried the below things so far:
<DockPanel.Resources>
<DataTemplate DataType="{x:Type src:Variation}">
<TextBlock Background="{Binding Path=color}" Height="15" Width="{Binding Path=elapsedtime}"/>
</DataTemplate>
<HierarchicalDataTemplate DataType = "{x:Type src:Track}" ItemsSource = "{Binding Path=Vars}">
<StackPanel/>
</HierarchicalDataTemplate>
</DockPanel.Resources>
public class TrackList : ViewModel
{
private ICollection<Track> tracks;
private Track selectedTrack;
public string Name
{ get; set; }
public TrackList()
{
this.tracks = new List<Track>();
this.tracks.Add(new Track("T1"));
this.tracks.Add(new Track("T2"));
Name = "Track List";
selectedTrack = tracks.ElementAt(1);
}
public ICollection<Track> Tracks
{
get { return this.Tracks; }
set { this.Tracks = value; }
}
public Track SelectedTrack
{
get { return this.selectedTrack; }
set
{
if (this.selectedTrack != value)
{
this.selectedTrack = value;
this.OnPropertyChanged("SelectedTrack");
}
}
}
}
public class Track : ViewModel
{
private ICollection<Variation> vars;
private Variation selectedVar;
public string Name { get; set; }
public Track()
{
Init();
}
public Track(string p)
{
// TODO: Complete member initialization
this.Name = p;
Init();
}
private void Init()
{
this.vars = new List<Variation>();
this.vars.Add(new Variation("var1", 20, Brushes.Red));
this.vars.Add(new Variation("var2", 60, Brushes.Green));
this.vars.Add(new Variation("var3", 40, Brushes.Khaki));
this.vars.Add(new Variation("var4", 120, Brushes.Aqua));
selectedVar = vars.ElementAt(1);
}
public ICollection<Variation> Vars
{
get { return this.vars; }
set { this.vars = value; }
}
public Variation SelectedVar
{
get { return this.selectedVar; }
set
{
if (this.selectedVar != value)
{
this.selectedVar = value;
this.OnPropertyChanged("SelectedVar");
}
}
}
}
public class Variation : ViewModel
{
public int elapsedtime { get; set; }
public string Name { get; set; }
public System.Windows.Media.Brush color { get; set; }
public Variation(string varname)
{
Name = varname;
}
public Variation(string name, int time, System.Windows.Media.Brush br)
{
// TODO: Complete member initialization
this.Name = name;
this.elapsedtime = time;
this.color = br;
}
}
public abstract class ViewModel : INotifyPropertyChanged
{
private readonly Dispatcher _dispatcher;
protected ViewModel()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected Dispatcher Dispatcher
{
get { return _dispatcher; }
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged(this, e);
}
protected void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
Please let me know for any farther information.
Thanks
I don't think you need HierarchicalDataTemplate, your tree has known number of levels (TrackList>Track>Variation). You can simply do this:
<DockPanel.Resources>
<DataTemplate DataType="{x:Type src:Variation}">
<TextBlock Background="{Binding Path=color}" Height="15" Width="{Binding Path=elapsedtime}"/>
</DataTemplate>
<DataTemplate DataType="{x:Type src:Track}">
<StackPanel>
<TextBlock Text="{Binding Name}"/>
<ItemsControl ItemsSource="{Binding Vars}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</StackPanel>
</DataTemplate>
</DockPanel.Resources>
<ItemsControl ItemsSource="{Binding Tracks}" />
Where ItemsControl bind to Tracks property of the TrackList (ItemsControl.DataContext = TrackList).
You can represent your hierarchical data using a TreeView:
<TreeView ItemsSource="{Binding Tracks}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type src:Track}" ItemsSource="{Binding Vars}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>

How to make binding to WPF TreeView?

I have a TreeView with Binding, but in the TreeView only 1st level items are shown. I need a treeview =) I broke my head what is wrong.
Here is my code:
MainWindow.xaml
<TreeView Margin="2.996,10,214,10" ItemsSource="{Binding Path=Urls}" Grid.Column="1">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate>
<Grid>
<Rectangle Fill="{Binding Path=Color}" HorizontalAlignment="Left" Stroke="Black" VerticalAlignment="Top" Height="20" Width="20"/>
<TextBlock Text="{Binding Path=AbsoluteUrl}" Margin="25,0,0,0" />
</Grid>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Path=AbsoluteUrl}" />
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
MainViewModel.cs (part)
public ObservableCollection<Url> Urls { get; set; }
public MainWindowViewModel()
{
Urls = new ObservableCollection<Url>();
}
Url.cs
class Url : INotifyPropertyChanged
{
public Url() { }
public Url(string absoluteUrl, bool isBroken, string color)
{
AbsoluteUrl = absoluteUrl;
IsBroken = isBroken;
Color = color;
}
enum Status { Working, Broken };
private ObservableCollection<Url> childUrlsValue = new ObservableCollection<Url>();
public ObservableCollection<Url> ChildUrls
{
get
{
return childUrlsValue;
}
set
{
childUrlsValue = value;
}
}
private string _absoluteUrl;
public string AbsoluteUrl
{
get { return _absoluteUrl; }
set
{
if (_absoluteUrl != value)
{
_absoluteUrl = value;
OnPropertyChanged("AbsoluteUrl");
}
}
}
private bool _isBroken;
public bool IsBroken
{
get { return _isBroken; }
set
{
if (_isBroken != value)
{
_isBroken = value;
OnPropertyChanged("IsBroken");
}
}
}
private string _color;
public string Color
{
get { return _color; }
set
{
if (_color != value)
{
_color = value;
OnPropertyChanged("Color");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And just about this i'm adding items to Urls:
Url DataGridTopic = new Url(startUrl.ToString(), true, "red");
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
DataGridTopic.ChildUrls.Add(
new Url(startUrl.ToString(), true, "red"));
Urls.Add(DataGridTopic);
You will have to tell the HierarchicalDataTemplate where to get the child items of a node from by using its ItemsSource property.
In your case:
<HierarchicalDataTemplate
DataType="{x:Type my:Url}"
ItemsSource="{Binding Path=ChildUrls}"
>
...
</HierarchicalDataTemplate>
Note also the usage od the DataType attribute, which often will become a necessity if the levels of the tree are made of different object types (a tree of directories and files would be such an example). However, i am not sure whether this would apply to your scenario or not.

ListView's item insert animations in WinRT

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);
}
}
}
}

Categories