TreeViewItem MVVM IsSelected in Xaml doesn't send value to View-Model - c#

I have a problem with IsSelected property. It doesn't send values from view to view-model. I posted my code below
ViewModel:
public class Viewmodel : INotifyPropertyChanged
{
private ObservableCollection<int> seznam;
public ObservableCollection<int> Seznam
{
get { return seznam; }
set
{
seznam = value;
}
}
public Viewmodel()
{
Seznam = new ObservableCollection<int>();
for (int i = 0; i < 3; i++)
{
Seznam.Add(i);
}
}
bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
isSelected = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
View:
<TreeView ItemsSource="{Binding Seznam}">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
It still doesn't stop at breakpoint that I put on get { return isSelected; }

With your updated post, it is clear that you haven't implemented your view models correctly. In particular, your TreeView.ItemsSource is bound to the Seznam property of your only view model. This is a collection of int values.
This means that the data context for each item container in the TreeView, where you attempt to bind to the IsSelected property, is an int value. And of course, int values don't even have an IsSelected property.
(By the way, I am skeptical about your claim that "There are no binding errors". If you looked at the debug output, you certainly should have seen a binding error, where attempting to bind to the non-existent IsSelected property.)
And think about this for a moment: supposing the item container did manage to bind to the Viewmodel.IsSelected property. How many item containers do you think there are? And how many instances of Viewmodel do you think there are? You should believe that there are many item containers, i.e. one for each item in your collection. And that there is just one instance of Viewmodel. So, how would all those items' selection state even map to the single Viewmodel.IsSelected property?
The right way to do this would be to create a separate view model object for the collection, with a property for your int value, as well as properties for the IsSelected and IsExpanded states (since you originally had mentioned wanting both).
Here is the example I wrote earlier just to prove to myself that the usual approach would work as expected. You should not have any trouble adapting it to suit your needs…
Per-item view model:
class TreeItemViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<TreeItemViewModel> Items { get; }
= new ObservableCollection<TreeItemViewModel>();
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set { _UpdateField(ref _isSelected, value, _OnBoolPropertyChanged); }
}
private bool _isExpanded;
public bool IsExpanded
{
get { return _isExpanded; }
set { _UpdateField(ref _isExpanded, value, _OnBoolPropertyChanged); }
}
private void _OnBoolPropertyChanged(bool obj)
{
_RaisePropertyChanged(nameof(FullText));
}
private string _text;
public string Text
{
get { return _text; }
set { _UpdateField(ref _text, value, _OnTextChanged); }
}
private void _OnTextChanged(string obj)
{
_RaisePropertyChanged(nameof(FullText));
}
public string FullText
{
get { return $"{Text} (IsSelected: {IsSelected}, IsExpanded: {IsExpanded})"; }
}
}
Main view model for window:
class MainViewModel : NotifyPropertyChangedBase
{
public ObservableCollection<TreeItemViewModel> Items { get; }
= new ObservableCollection<TreeItemViewModel>();
public ICommand ClearSelection { get; }
public MainViewModel()
{
ClearSelection = new ClearSelectionCommand(this);
}
class ClearSelectionCommand : ICommand
{
private readonly MainViewModel _parent;
public ClearSelectionCommand(MainViewModel parent)
{
_parent = parent;
}
#pragma warning disable 67
public event EventHandler CanExecuteChanged;
#pragma warning restore 67
public bool CanExecute(object parameter)
{
return true;
}
public void Execute(object parameter)
{
_parent._ClearSelection();
}
}
private void _ClearSelection()
{
_ClearSelection(Items);
}
private static void _ClearSelection(IEnumerable<TreeItemViewModel> collection)
{
foreach (TreeItemViewModel item in collection)
{
_ClearSelection(item.Items);
item.IsSelected = false;
item.IsExpanded = false;
}
}
}
XAML for window:
<Window x:Class="TestSO44513864TreeViewIsSelected.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:p="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:l="clr-namespace:TestSO44513864TreeViewIsSelected"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<l:MainViewModel>
<l:MainViewModel.Items>
<l:TreeItemViewModel Text="One">
<l:TreeItemViewModel.Items>
<l:TreeItemViewModel Text="One A"/>
<l:TreeItemViewModel Text="One B"/>
</l:TreeItemViewModel.Items>
</l:TreeItemViewModel>
<l:TreeItemViewModel Text="Two"/>
<l:TreeItemViewModel Text="Three"/>
</l:MainViewModel.Items>
</l:MainViewModel>
</Window.DataContext>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<Button Content="Clear Selection" Command="{Binding ClearSelection}"
HorizontalAlignment="Left"/>
<TreeView ItemsSource="{Binding Items}" Grid.Row="1">
<TreeView.ItemContainerStyle>
<p:Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
</p:Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="l:TreeItemViewModel"
ItemsSource="{Binding Items}">
<TextBlock Text="{Binding FullText}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Grid>
</Window>
And for completeness…
The boilerplate base class for INotifyPropertyChanged implementation:
class NotifyPropertyChangedBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void _UpdateField<T>(ref T field, T newValue,
Action<T> onChangedCallback = null,
[CallerMemberName] string propertyName = null)
{
if (EqualityComparer<T>.Default.Equals(field, newValue))
{
return;
}
T oldValue = field;
field = newValue;
onChangedCallback?.Invoke(oldValue);
_RaisePropertyChanged(propertyName);
}
protected void _RaisePropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

Instead of using the IsSelected on every node in the tree, use the TreeView.SelectedItem on the TreeView itself. From here you can bind, but the property is readonly.

Related

MVVM ListView MultiBinding SelectedItems + SelectedItem (ListView) + SelectedItem (ComboBox) to TextBox.Text. Does not update properly

I am trying to MultiBind the SelectedItems (ListView) and SelectedItem or SelectedCategory in my ViewModel (ComboBox) to a readonly TextBox. The OutputConverter just checks if there is at least one item selected (ListView) and TypeData (ComboBox) selected before creating the text for the TextBox.
However, if I try it only with that the TextBox only updates when the ComboBox.SelectedItem changes not when SelectedItems inside ListView changes.
So I also included from my ViewModel SelectedEntry (ListView) (which is same as SelectedItem) as a Binding for the MultiBinding.
Now I get the following:
Explanation:
The Selection is always one step behind and uses the previous SelectedItems from the ListView to bind to the TextBox.Text. Even when I am selecting multiple entries via CTRL or Shift + Click. However, if the ComboBox.SelectedItem changes it updates the TextBox as intended.
How do I get the behaviour if the Selection changes inside the ListView the TextBox immediately updates its content accordingly (preferably I would like to use the SelectedEntries of my ViewModel and not the SelectedItems of the ListView and if possible in a MVVM compliant way)?
Edit:
I noticed when the Converter is called the SelectedEntry (implements
INotifyPropertyChanged) is updated but the SelectedEntries
(ObservableCollection and implements INotifyPropertyChanged) is not.
I have also included a SelectionChanged event that calls a command
and passes the SelectedItems as a parameter to the command. If that
might help but I would rather like to have a proper binding that
updates accordingly.
Code:
Model TypeData (ComboBox):
public class TypeData : INotifyPropertyChanged
{
public enum Type
{
NotSet = '0',
A = 'A',
B = 'B',
C = 'C'
}
private string name;
public string Name
{
get { return name; }
set
{
name = value;
//OnPropertyChanged("Name");
OnPropertyChanged(nameof(Name));
}
}
private Type category;
public Type Category
{
get { return category; }
set { category = value; }
}
public TypeData(string name)
{
Name = name;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public override string ToString()
{
return Name;
}
}
Model Entry (ListView):
public class Entry : INotifyPropertyChanged
{
private string title;
public string Title
{
get { return title; }
set
{
title = value;
OnPropertyChanged(nameof(Title));
}
}
private string author;
public string Author
{
get { return author; }
set
{
author = value;
OnPropertyChanged(nameof(Author));
}
}
private string year;
public string Year
{
get { return year; }
set
{
year = value;
OnPropertyChanged(nameof(Year));
}
}
public Entry(string title, string author, string year)
{
Title = title;
Author = author;
Year = year;
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ViewModel:
public class MainViewModel
{
public ObservableCollection<Entry> Entries { get; set; }
public Entry SelectedEntry { get; set; }
public ObservableCollection<Entry> SelectedEntries { get; set; }
public ObservableCollection<TypeData> Types { get; set; }
private TypeData selectedCategory;
public TypeData SelectedCategory { get; set; }
public RelayCommand<object> SelectionChangedCommand { get; set; }
public MainViewModel()
{
Entries = new ObservableCollection<Entry>
{
new Entry("Title1", "Author1", "Year1"),
new Entry("Title2", "Author2", "Year2"),
new Entry("Title3", "Author3", "Year3"),
new Entry("Title4", "Author4", "Year4"),
};
Types = new ObservableCollection<TypeData>
{
new TypeData("A"),
new TypeData("B"),
new TypeData("C"),
};
SelectionChangedCommand = new RelayCommand<object>(items =>
{
var selectedEntries = (items as ObservableCollection<object>).Cast<Entry>();
SelectedEntries = new ObservableCollection<Entry>(selectedEntries);
});
}
}
XAML:
<Window x:Class="MvvmMultiBinding.View.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:MvvmMultiBinding"
xmlns:m="clr-namespace:MvvmMultiBinding.Model"
xmlns:vm="clr-namespace:MvvmMultiBinding.ViewModel"
xmlns:conv="clr-namespace:MvvmMultiBinding.View.Converter"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<vm:MainViewModel></vm:MainViewModel>
</Window.DataContext>
<Window.Resources>
<conv:OutputConverter x:Key="OutputConverter"/>
</Window.Resources>
<Grid>
<DockPanel>
<ListView Name="ListViewEntries" ItemsSource="{Binding Entries}" SelectedItem="{Binding SelectedEntry}" DockPanel.Dock="Top">
<ListView.View>
<GridView>
<GridViewColumn Header="Title" Width="250" DisplayMemberBinding="{Binding Title}" />
<GridViewColumn Header="Author" Width="150" DisplayMemberBinding="{Binding Author}" />
<GridViewColumn Header="Year" Width="50" DisplayMemberBinding="{Binding Year}" />
</GridView>
</ListView.View>
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding DataContext.SelectionChangedCommand, ElementName=ListViewEntries}"
CommandParameter="{Binding SelectedItems, ElementName=ListViewEntries}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListView>
<ComboBox ItemsSource="{Binding Types}" SelectedItem="{Binding SelectedCategory}" MinWidth="200" DockPanel.Dock="Right"/>
<TextBox IsReadOnly="True" DockPanel.Dock="Left">
<TextBox.Text>
<MultiBinding Converter="{StaticResource OutputConverter}">
<Binding ElementName="ListViewEntries" Path="SelectedItems" Mode="OneWay"/>
<!--<Binding Path="SelectedEntries" Mode="OneWay"/>-->
<Binding Path="SelectedCategory" Mode="OneWay"/>
<!-- Without it converter is not called after selection changes -->
<Binding Path="SelectedEntry" Mode="OneWay"/>
</MultiBinding>
</TextBox.Text>
</TextBox>
</DockPanel>
</Grid>
OutputConverter:
public class OutputConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
System.Collections.IList items = (System.Collections.IList)values[0];
var entries = items.Cast<Entry>();
TypeData type = values[1] as TypeData;
List<Entry> selectedEntries = new List<Entry>();
foreach (var entry in entries)
{
selectedEntries.Add(entry);
}
StringBuilder sb = new StringBuilder();
// ComboBox and Selection must not be empty
if (type != null && selectedEntries.Count > 0)
{
foreach (var selectedEntry in selectedEntries)
{
sb.AppendFormat("{0} {1}\n\n", selectedEntry.Author, type);
}
}
return sb.ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
I would suggest giving your Entry Class an IsSelected property (Bound to the IsSelectedProperty of a ListViewItem). When the selection changes you can just iterate through your collection (bound to the ListView) and check if they are selected or not. Like this (excuse the MvvmLight, RelayCommand = ICommand, ViewModelBase extends ObservableObject):
ViewModel:
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
TestItemCollection = new ObservableCollection<TestItem>
{
new TestItem("Test1"),
new TestItem("Test2"),
new TestItem("Test3")
};
}
private TestItem m_selectedItemProperty;
public TestItem SelectedItemProperty
{
get
{
return m_selectedItemProperty;
}
set
{
m_selectedItemProperty = value;
RaisePropertyChanged("SelectedItemProperty");
}
}
public ObservableCollection<TestItem> TestItemCollection
{
get;
set;
}
public RelayCommand SelectionChanged
{
get { return new RelayCommand(OnSelectionChanged); }
}
private void OnSelectionChanged()
{
foreach (var item in TestItemCollection)
{
if (item.IsSelected)
Console.WriteLine("Name: " + item.Name);
}
}
}
I printed the names out here but you can also just add them to a string property and bind it to your text box or add the items to a collection (maybe bound to a ListBox or ItemsControl showing the selected entries).
TestItem:
public class TestItem : ObservableObject
{
public TestItem(string a_name)
{
m_name = a_name;
}
private string m_name;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
RaisePropertyChanged("Name");
}
}
private bool m_isSelected;
public bool IsSelected
{
get
{
return m_isSelected;
}
set
{
m_isSelected = value;
RaisePropertyChanged("IsSelected");
}
}
}
View:
<Window x:Class="WpfAppTests.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:WpfAppTests"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
mc:Ignorable="d"
xmlns:modelNoMvvmLight="clr-namespace:WpfAppTests"
xmlns:modelMvvmLight="clr-namespace:WpfAppTests.ViewModel"
Title="MainWindow" Height="350" Width="525" >
<Window.DataContext>
<modelMvvmLight:MainViewModel/>
</Window.DataContext>
<StackPanel>
<ListView Name="ListView" ItemsSource="{Binding TestItemCollection}" SelectedItem="{Binding SelectedItemProperty}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged">
<i:InvokeCommandAction Command="{Binding SelectionChanged}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem" >
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
</StackPanel>
</Window>

Maintain checkbox state while the app is running in WPF

I'm working in MVVM, WPF and I have a popup; inside this popup is a listbox and inside the listbox I have a checkbox. The problem is: if I uncheck an item from the list box and click outside, popup disappears; if a I click again the checkbox is reseted at its initial value (all the items become checked).
So, how can I maintain the state of the popup set and stop its resetting while the app is running ? Can I do this through XAML ?
here is the code:
public class CheckedListItem<T> : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private bool isChecked = false;
private T item;
public CheckedListItem()
{ }
public CheckedListItem(T item, bool isChecked)
{
this.item = item;
this.isChecked = isChecked;
}
public T Item
{
get { return item; }
set
{
item = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Item"));
}
}
public bool IsChecked
{
get { return isChecked; }
set
{
isChecked = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("IsChecked"));
}
}
}
the viewModel:
private void OnApplyFiltersCommandRaised(object obj)
{
if (FilterElement.Contains("ClassView"))
{
switch (FilterElement)
{
case "buttonClassViewClassFilter":
FilteredClassViewItems.Clear();
FilteredFieldViewItems.Clear();
foreach (var filterItem in FilterItems)
{
if (filterItem.IsChecked == true)
{
FilteredClassViewItems.Add(classViewItems.First(c => c.ClassName == filterItem.Item));
FilteredFieldViewItems.Add(fieldViewItems.First(c => c.ClassName == filterItem.Item));
}
}
break;
...
public ObservableCollection<CheckedListItem<string>> FilterItems
{
get
{
return filterItems;
}
set
{
filterItems = value;
SetPropertyChanged("FilterItems");
}
}
the XAML part:
<ListBox x:Name="listBoxPopupContent"
Height="250"
ItemsSource="{Binding FilterItems}"
BorderThickness="0"
ScrollViewer.VerticalScrollBarVisibility="Auto">
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="FontSize" Value="8" />
<Setter Property="IsSelected" Value="{Binding IsChecked, Mode=TwoWay}" />
</Style>
</ListBox.Resources>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}"
Content="{Binding Item}"
Command="{Binding DataContext.ApplyFiltersCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type ListBox}}}"
CommandParameter="{Binding IsChecked,
RelativeSource={RelativeSource Self},
Mode=OneWay}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Thanks in advance !
If you want to keep the state, you can just create a new view that will contain your listbox. Then your popup will be
<Popup>
<views:MyListBoxview>
</Popup>
where views is the path where wpf can find MyListBoxview.
This is an example of how you can do MyListBoxView. First of all, add a new usercontrol to your project. Then you create:
<ListBox ItemSource = {Binding MyCollectionOfItem}>
<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked = {Binding IsItemChecked} Content = {Binding Name}/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
You will need to assign to this view a viewmodel that will of course implement INotifyPropertyChanged and that will have these this class defined inside it (also this class will implement INotifyPropertyChanged)
public class MyItem : INotifyPropertyChanged
{
public void SetPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
private bool isItemChecked = false;
public bool IsItemChecked
{
get { return isItemChecked; }
set
{
isItemChecked = value;
SetPropertyChanged("IsItemChecked");
}
}
private string name ;
public string Name
{
get { return Name; }
set
{
name = value;
SetPropertyChanged("Name");
}
}
}
finally, the viewmodel that will represent the state of the popup will have inside this property
private ObservableCollection<MyItem> myCollectionOfItem = new ObservableCollection<MyItem>();
public ObservableCollection<MyItem> MyCollectionOfItem
{
get { return myCollectionOfItem; }
set
{
myCollectionOfItem = value;
SetPropertyChanged("MyCollectionOfItem");
}
}
I usually handle this kind of problem modelling properly the object that i need to bind to my controls in WPF

Custom WPF TreeView Binding

I am trying to bind a collection of custom objects to a tree view's ItemSource in WPF with no success.
Here is the MainWindow.xaml:
<Window
x:Class="AoiImageLift.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:AoiImageLift.UI.ViewModels"
Height="500"
Width="500">
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<TreeView ItemsSource="{Binding TreeViewViewModel.ProcessList}"/>
</Window>
Here is the App.xaml:
</Application>
</Application.Resources>
<!-- TreeView Style -->
<Style TargetType="{x:Type TreeView}">
<Setter Property="ScrollViewer.CanContentScroll" Value="True"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
<Setter Property="SelectedValuePath" Value="Wafer"/>
<Setter Property="ItemTemplate">
<Setter.Value>
<HierarchicalDataTemplate ItemsSource="{Binding ProcessList}">
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate>
<TextBlock
FontFamily="SegoeUI"
Foreground="MidnightBlue"
Text="{Binding Wafer}"/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<TextBlock
Text="{Binding ProcessNumber}"
FontFamily="SegoeUI"
Foreground="MidnightBlue"/>
</HierarchicalDataTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
</Application>
Here is the MainWindowViewModel.cs:
public class MainWindowViewModel : ViewModel
{
private WaferSelectionTreeViewViewModel treeViewViewModel;
public MainWindowViewModel()
{
BackgroundWorker initThread = new BackgroundWorker();
initThread.DoWork += (sender, e) =>
{
e.Result = new SingulationOneTable().GetWaferList();
};
initThread.RunWorkerCompleted += (sender, e) =>
{
TreeViewViewModel = new WaferSelectionTreeViewViewModel(
(List<string>) e.Result);
};
initThread.RunWorkerAsync();
}
public WaferSelectionTreeViewViewModel TreeViewViewModel
{
get { return treeViewViewModel; }
set
{
treeViewViewModel = value;
OnPropertyChanged("TreeViewViewModel");
}
}
}
FYI, this line of code...
e.Result = new SingulationOneTable().GetWaferList();
...simply returns a large list of strings. That list of strings is then passed into the constructor of the WaferSelectionTreeViewViewModel class.
Here is the WaferSelectionTreeViewViewModel.cs:
public class WaferSelectionTreeViewViewModel : ViewModel
{
private ObservableCollection<Process> processList;
public class TreeViewItemBase : ViewModel
{
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set
{
if (value != isSelected)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private bool isExpanded;
public bool IsExpanded
{
get { return isExpanded; }
set
{
if (value != isExpanded)
{
isExpanded = value;
OnPropertyChanged("IsExpanded");
}
}
}
}
public class Process : TreeViewItemBase
{
private string name;
public Process(string name)
{
this.name = name;
this.Children = new ObservableCollection<string>();
}
public string Name { get { return name; } }
public ObservableCollection<string> Children { get; set; }
}
public WaferSelectionTreeViewViewModel(List<string> waferList)
{
processList = new ObservableCollection<Process>();
List<string> procList = new List<string>();
foreach (string wafer in waferList)
{
procList.Add(wafer.Substring(0, 4));
}
IEnumerable<string> distintProcessList = procList.Distinct();
foreach (string process in distintProcessList)
{
Process newProcess = new Process(process);
List<string> wafersInProcess = waferList.FindAll(
x => x.Substring(0, 4) == process);
foreach (string waferInThisProcess in wafersInProcess)
{
newProcess.Children.Add(waferInThisProcess);
}
}
}
public ObservableCollection<Process> ProcessList
{
get
{
return processList;
}
set
{
processList = value;
OnPropertyChanged("ProcessList");
}
}
}
Can anyone figure out why the items are not showing up in the tree view??
Regards,
Kyle
There are a couple of errors in your bindings. If you run your application from Visual Studio, you'll probably see one or more messages like this in the Output window:
System.Windows.Data Error: 40 : BindingExpression path error: (...)
Firstly, each root item is bound to a Process object from TreeViewViewModel.ProcessList and it's told to display a property called ProcessNumber, but there is no such property, at least not in the code you posted. So I'm guessing the process items are showing up in the TreeView, but they're blank.
Secondly, your HierarchicalItemTemplate says that the list of child items can be found in a property called ProcessList. But each root item is a Process, which doesn't have that property, so no child items are displayed. You probably mean:
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
Now, Process.Children is a simple list of strings, so you don't need to include the <HierarchicalDataTemplate.ItemTemplate> part (and of course, strings don't have the Wafer property that template is looking for).

C# Bindings not working to Property<T>

I am currently trying to follow MVVM in C# 4, but having troubles with the bindings working.
Starting from the bottom, here is my Property class that should take care of the property changed for XAML bindings:
namespace Visualizer.MVVM
{
public class Property<T> : DependencyObject, INotifyPropertyChanged
{
//private T _Value;
public T Value
{
get { return (T) GetValue(ValueProperty); }
set
{
SetValue(ValueProperty, value);
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged()
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("Value"));
}
}
public Property(T val)
{
Value = val;
}
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value", typeof(T), typeof(Property<T>));
}
}
My ViewModel for the control looks like this and is instantiated in MainWindow.xaml.cs:
public class CheckboxControlVM
{
public Property<bool> IsChecked { get; set; }
public Property<string> Name { get; set; }
public CheckboxControlVM(bool isChecked, string name)
{
IsChecked = new Property<bool>(isChecked);
Name = new Property<string>(name);
}
}
The control has no code-behind, so here is the XAML for it:
<UserControl x:Class="Visualizer.MVVM.Checkbox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Visualizer.MVVM"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<StackPanel Orientation="Horizontal" x:Name="LayoutRoot">
<CheckBox IsChecked="{Binding Path=IsChecked.Value, Mode=TwoWay}"/>
<TextBlock Text="{Binding Path=Name.Value, Mode=OneWay}"/>
</StackPanel>
</UserControl>
Finally, here is the binding in MainWindow.xaml:
<mvvm:Checkbox DataContext="{Binding Realtime}"/>
I have been stuck on this for a lot longer than I should be and am fairly certain its just a simple issue. Any ideas?
I don't quite get your objective of what you want to achieve with that property design. Normally I don't do that in WPF so I'm not quite sure whether this help or not.
Usually, I do implement INotifyPropertyChanged in ViewModel level, not in the attribute owned by VM. Example:
public class ViewModel : INotifyPropertyChanged{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Second, I do not use DependencyProperty unless I make a WPF user control. So I use private property and trigger the OnPropertyChanged with the property name.
private string _name;
public string Name{
set{
_name = value;
OnPropertyChanged("Name");
}
}
Last, in the XAML, I use binding with UpdateSourceTrigger=PropertyChanged.
<TextBlock Text="{Binding Path=Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Maybe you can try to add UpdateSourceTrigger=PropertyChanged in your binding, but I am not sure if it will work.
try this
public class CheckboxControlVM
{
bool _isChecked = false;
string _name ;
public Property<bool> IsChecked { get { return _isChecked} set { _isChecked=value;} }
public Property<string> Name { get { return _name } set { _name =value;} }
public CheckboxControlVM(bool isChecked, string name)
{
_isChecked = isChecked;
_name = name;
IsChecked = new Property<bool>(_isChecked);
Name = new Property<string>(_name);
}
}

IsExpanded only works on first level of TreeView

I'm using a TreeView with HierarchicalDataTemplate but can't get the IsExpanded property working for higher levels than the first. Here's my xaml:
<TreeView>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Text}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
In my ResourceDictionary I have:
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
</Style>
what makes the first order work.
In higher indention levels IsExpanded is always false because the PropertyChangedEventHandler is not fired for children.
Here's my class:
public class ListItem : INotifyPropertyChanged
{
private bool isExpanded;
public bool IsExpanded
{
get { return isExpanded; }
set
{
if (isExpanded != value)
{
isExpanded = value;
SendPropertyChanged("IsExpanded");
}
}
}
private void SendPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ObservableCollection<ListItem> Children { get; set; }
...
}
EDIT: I'm very sorry, my corrected code is working!
If you want to automatically expand all the children as well the target item then you need to propogate the change downwards yourself, do something like this....
public bool IsExpanded
{
get { return isExpanded; }
set
{
if (isExpanded != value)
{
isExpanded = value;
if (isExpanded)
{
foreach(ListItem child in Children)
child.IsExpanded = true;
}
SendPropertyChanged("IsExpanded");
}
}
}

Categories

Resources