Adding context menu to leaf node in TreeView WPF - wpf

In my WPF application, I want to add a context menu and its handler in ViewModel to the leaf nodes of my TreeView control. Here is how I have added the TreeView Control.
<TreeView Name="treePads" ItemsSource="{Binding pads}" Width="190">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type self:Pad}" ItemsSource="{Binding Members}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Text=" [" Foreground="Blue" />
<TextBlock Text="{Binding Members.Count}" Foreground="Blue" />
<TextBlock Text="]" Foreground="Blue" />
</StackPanel>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type self:PadInfo}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="["></TextBlock>
<TextBlock Text="{Binding SlotID}" />
<TextBlock Text="] ["></TextBlock>
<TextBlock Text="{Binding WellID}" />
<TextBlock Text="]"></TextBlock>
</StackPanel>
</DataTemplate>
</TreeView.Resources>
</TreeView>
Here is how the output of this code looks like:
I want to add a ContextMenu having two options: Rename, Delete and add there event handlers to the ViewModel. How can I do that?

This is good article on TreeView
http://www.codeproject.com/Articles/26288/Simplifying-the-WPF-TreeView-by-Using-the-ViewMode
Below I have shared a sample app which has a Rename Context Menu. The sample should help you to fix your problem.
XAML:
<TreeView Name="treeView">
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<!--<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />-->
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Header="Rename" Command="{Binding RenameCommand}"/>
</ContextMenu>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="FontWeight" Value="Bold" />
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubElements}">
<StackPanel Orientation="Horizontal">
<!--<Image Margin="2" Source="{Binding ImageLocation}" Height="30" Width="30"/>-->
<TextBlock Margin="2" Text="{Binding HeaderText}" ></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace WpfApplication1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<TreeViewElement> elements = new List<TreeViewElement>();
TreeViewElement mainElement = new TreeViewElement() { ImageLocation = "Images/1.png", HeaderText = "MainElement1" };
mainElement.SubElements = new List<TreeViewElement>();
mainElement.SubElements.Add(new TreeViewElement() { ImageLocation = "Images/2.png", HeaderText = "SubElement1" });
mainElement.SubElements.Add(new TreeViewElement() { ImageLocation = "Images/2.png", HeaderText = "SubElement2", BackgroundColor = "Blue" });
elements.Add(mainElement);
TreeViewElement mainElement2 = new TreeViewElement() { HeaderText = "MainElement2" };
elements.Add(mainElement2);
this.treeView.ItemsSource = elements;
}
}
public class TreeViewElement
{
public string ImageLocation { get; set; }
public string HeaderText { get; set; }
public string BackgroundColor { get; set; }
public List<TreeViewElement> SubElements { get; set; }
private ICommand _RenameCommand;
public ICommand RenameCommand
{
get {
if (_RenameCommand == null)
{
_RenameCommand = new RelayCommand((o) =>
{
// Your logic should go here
MessageBox.Show("HeaderText is " +HeaderText);
});
}
return _RenameCommand; }
}
}
public class RelayCommand : ICommand
{
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
#region Constructors
public RelayCommand(Action<object> execute)
: this(execute, null)
{
}
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
}
}

Related

Adding Icon to Dynamic Menu item in WPF

I am trying to generate MenuItem dynamically.
How can I Bind that in Style?
Here is the code.
XAML
<Window.Resources>
<Image x:Key="Image.Icon"
Source="pack://application:,,,/DynamicMenu;component/icon.png"/>
</Window.Resources>
<DockPanel>
<Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}">
<Menu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding Command}" />
<Setter Property="Icon">
<Setter.Value>
<Image Source="{Binding ImagePath}" Width="12" Height="12" />
</Setter.Value>
</Setter>
</Style>
</Menu.ItemContainerStyle>
<Menu.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}"
ItemsSource="{Binding Path=MenuItems}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Header}"/>
</StackPanel>
</HierarchicalDataTemplate>
</Menu.ItemTemplate>
</Menu>
<Grid>
</Grid>
</DockPanel>
ViewModel
public class MenuItemViewModel
{
private readonly ICommand _command;
public MenuItemViewModel()
{
_command = new CommandViewModel(Execute);
}
public string Header { get; set; }
public string Param1 { get; set; }
public string ImagePath { get; set; }
public ObservableCollection<MenuItemViewModel> MenuItems { get; set; }
public ICommand Command
{
get {return _command; }
}
private void Execute()
{
MessageBox.Show("Clicked at " + Header + Param1);
}
}
Command
public class CommandViewModel : ICommand
{
private readonly Action _action;
public CommandViewModel(Action action)
{
_action = action;
}
public void Execute(object o)
{
_action();
}
public bool CanExecute(object o)
{
return true;
}
public event EventHandler CanExecuteChanged
{
add { }
remove { }
}
}
I want to add a different icon for different MenuItem.
So I am planning to pass the icon file as MenuItemViewModel property.
Need a way to bind the icon property to the MenuItem.
Thanks.
I find a solution for my question:
<MenuItem Header="{Binding Path=Header}" Command="{Binding PresentationTripLegCommand}">
<MenuItem.Icon>
<Image Source="{Binding IconFileName}" Height="16" />
</MenuItem.Icon>
</MenuItem>

In WPF,How to add radio button , checkbox, comboBox based on the type which is configured in the database?

Totally i am new to WPF, I need to solve the problem. Could anybody give me a sample xaml code without using code-behind.
Based on the questType (Check,radio, combo) Control need to be created based on the ObserverableCollection.
public class Order
{
public int OrderCode {get;set;}
public string Description {get;set;}
public ObserverableCollection<question> Questions{get;set;}
}
public class question
{
public string questType {get;set;}
public string Question {get;set;}
public ObserverableCollection<Answer> Answers {get;set;}
}
public class Answer
{
public string Ans{get; set;}
}
Based on the questType (Check,radio, combo)
Control need to be created based on the ObserverableCollection.
example:
1001 Pencil Gender? oMale oFemale oOther
[]Checkbox1 []Checkbox2
1002 Pen Fasting? oYes oNo
Here is how I would do it:
Code behind:
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
namespace Ans
{
public class Order
{
public int OrderCode { get; set; }
public string Description { get; set; }
public ObservableCollection<Question> Questions { get; set; }
}
public class Question
{
public string questType { get; set; }
public string Label { get; set; }
public ObservableCollection<Answer> Answers { get; set; }
}
public class Answer
{
public string Ans { get; set; }
public bool IsSelected { get; set; }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Order
/// <summary>
/// Order Dependency Property
/// </summary>
public static readonly DependencyProperty OrderProperty =
DependencyProperty.Register("Order", typeof(Order), typeof(MainWindow),
new FrameworkPropertyMetadata((Order)null));
/// <summary>
/// Gets or sets the Order property. This dependency property
/// indicates ....
/// </summary>
public Order Order
{
get { return (Order)GetValue(OrderProperty); }
set { SetValue(OrderProperty, value); }
}
#endregion
public MainWindow()
{
InitializeComponent();
Order = new Order()
{
Questions = new ObservableCollection<Question>()
{
new Question()
{
questType = "Combo",
Label = "Combo",
Answers = new ObservableCollection<Answer>()
{
new Answer(){Ans = "Female"},
new Answer(){Ans = "Male"}
}
},
new Question()
{
questType = "Check",
Label = "Multi",
Answers = new ObservableCollection<Answer>()
{
new Answer(){Ans = "Female"},
new Answer(){Ans = "Male"}
}
},
new Question()
{
questType = "Radio",
Label = "Radio",
Answers = new ObservableCollection<Answer>()
{
new Answer(){Ans = "Female"},
new Answer(){Ans = "Male"}
}
}
}
};
DataContext = this;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
foreach(Question q in Order.Questions)
{
Console.WriteLine( q.Label + " : " + string.Join(", " , q.Answers.Where(a=>a.IsSelected).Select(a=>a.Ans)) );
}
}
}
}
XAML:
<Window x:Class="Ans.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:Ans"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<DataTemplate x:Key="ComboQuestion">
<ComboBox ItemsSource="{Binding Answers}">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Ans}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
<ComboBox.ItemContainerStyle>
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
</DataTemplate>
<DataTemplate x:Key="CheckQuestion">
<ItemsControl ItemsSource="{Binding Answers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding Ans}" IsChecked="{Binding IsSelected, Mode=TwoWay}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
<DataTemplate x:Key="RadioQuestion">
<ItemsControl ItemsSource="{Binding Answers}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<RadioButton Content="{Binding Ans}" IsChecked="{Binding IsSelected, Mode=TwoWay}" GroupName="{Binding DataContext.Label, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DataTemplate>
</Window.Resources>
<Grid>
<ItemsControl ItemsSource="{Binding Order.Questions}" Grid.IsSharedSizeScope="True">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="Label"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}"/>
<ContentControl x:Name="ccQuestion" Grid.Column="1" Content="{Binding}" Margin="10"/>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding questType}" Value="Combo">
<Setter TargetName="ccQuestion" Property="ContentTemplate" Value="{StaticResource ComboQuestion}"/>
</DataTrigger>
<DataTrigger Binding="{Binding questType}" Value="Check">
<Setter TargetName="ccQuestion" Property="ContentTemplate" Value="{StaticResource CheckQuestion}"/>
</DataTrigger>
<DataTrigger Binding="{Binding questType}" Value="Radio">
<Setter TargetName="ccQuestion" Property="ContentTemplate" Value="{StaticResource RadioQuestion}"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Content="Order" Click="Button_Click" VerticalAlignment="Bottom"/>
</Grid>
</Window>
The only thing I've added to your model is IsSelected property that allows to know if this answer was selected.
The other important thing is the Radios. Their GroupName property defines the scope. So if no GroupName is set then when clicking on a radio in one question it will unselect radio in another question. I used Question label in my solution however it only works if labels are unique.
Another point is that data triggers are OK if you have 3-5 question types and if thay are only based on the questionType. However for more complex scenarios you can look for ItemTemplateSelector. It allows to write C# code that will select the template based on each item in ItemsControl.

Datagrid - Scrolling will crop images horizontally instead of vertically

I needed to invert Columns/Rows on my DataGrid (see WPF horizontal DataGrid and RotatedDataGrid)
Once I inverted it, I am having some weird effects on the images displayed inside my datagrid.
When I scroll down, the column 1 will crop the image by the left and a little on the right. The more I go down, the more it crops the left until there is nothing more.
How can I solve that ?
Here a full simple example if you want to test it (you just need to copy/paste it in a new project and scroll down to see the problem)
MainWindows.xaml
<Window x:Class="RotatedDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="150" Width="1000">
<Grid>
<DataGrid x:Name="MyRotatedDataGrid" HorizontalContentAlignment="Center"
ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible"
AutoGenerateColumns="True"
ItemsSource="{Binding Customers}">
<DataGrid.Resources>
<Style x:Key="DataGridBase" TargetType="Control">
<Setter Property="LayoutTransform">
<Setter.Value>
<TransformGroup>
<RotateTransform Angle="-90" />
<ScaleTransform ScaleX="1" ScaleY="-1" />
</TransformGroup>
</Setter.Value>
</Setter>
<Setter Property="TextOptions.TextFormattingMode" Value="Display" />
</Style >
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridBase}"/>
<Style TargetType="DataGridColumnHeader" BasedOn="{StaticResource DataGridBase}"/>
<Style TargetType="DataGridRowHeader" BasedOn="{StaticResource DataGridBase}"/>
</DataGrid.Resources>
<DataGrid.LayoutTransform>
<TransformGroup>
<RotateTransform Angle="90" />
<MatrixTransform Matrix="-1, 0, 0, 1, 0, 0" />
</TransformGroup>
</DataGrid.LayoutTransform>
<DataGrid.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=Name}" FontWeight="Bold" Padding="3"/>
</StackPanel>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.ContainerStyle>
<Style TargetType="{x:Type GroupItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type GroupItem}">
<Expander>
<Expander.Header>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Path=Name}"/>
<TextBlock Text="{Binding Path=ItemCount}" Margin="8,0,4,0"/>
<TextBlock Text="Items"/>
</StackPanel>
</Expander.Header>
<ItemsPresenter />
</Expander>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</GroupStyle.ContainerStyle>
</GroupStyle>
</DataGrid.GroupStyle>
</DataGrid>
</Grid>
</Window>
MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace RotatedDataGrid
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ICollectionView Customers { get; private set; }
public ICollectionView GroupedCustomers { get; private set; }
public MainWindow()
{
InitializeComponent();
var _customers = new List<Customer>
{
new Customer
{
FirstName = "Christian",
LastName = "Moser",
Gender = Gender.Male,
WebSite = new Uri("http://www.wpftutorial.net"),
ReceiveNewsletter = true,
Image = "Images/christian.jpg"
},
new Customer
{
FirstName = "Peter",
LastName = "Meyer",
Gender = Gender.Male,
WebSite = new Uri("http://www.petermeyer.com"),
Image = "Images/peter.jpg"
},
new Customer
{
FirstName = "Lisa",
LastName = "Simpson",
Gender = Gender.Female,
WebSite = new Uri("http://www.thesimpsons.com"),
Image = "Images/lisa.jpg"
},
new Customer
{
FirstName = "Betty",
LastName = "Bossy",
Gender = Gender.Female,
WebSite = new Uri("http://www.bettybossy.ch"),
Image = "Images/betty.jpg"
}
};
Customers = CollectionViewSource.GetDefaultView(_customers);
GroupedCustomers = new ListCollectionView(_customers);
GroupedCustomers.GroupDescriptions.Add(new PropertyGroupDescription("Gender"));
MyRotatedDataGrid.DataContext = this;
}
}
public enum Gender
{
Male,
Female
}
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private Gender _gender;
private Uri _webSite;
private bool _newsletter;
private string _image;
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
NotifyPropertyChanged("FirstName");
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
NotifyPropertyChanged("LastName");
}
}
public Gender Gender
{
get { return _gender; }
set
{
_gender = value;
NotifyPropertyChanged("Gender");
}
}
public Uri WebSite
{
get { return _webSite; }
set
{
_webSite = value;
NotifyPropertyChanged("WebSite");
}
}
public bool ReceiveNewsletter
{
get { return _newsletter; }
set
{
_newsletter = value;
NotifyPropertyChanged("Newsletter");
}
}
public string Image
{
get { return _image; }
set
{
_image = value;
NotifyPropertyChanged("Image");
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
#region Private Helpers
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
}
Ok I found how to solve it.
The transformation applied into the DataGridCell was creating this scrollviewer problem. To solve that, I removed the layout transform on the DataGridCell (by removing the BaseOn code) and I applied the transformation into the DataGridCell Template.
WRONG
<Style TargetType="DataGridCell" BasedOn="{StaticResource DataGridBase}"/>
RIGHT
<Style TargetType="DataGridCell">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type DataGridCell}">
<Grid>
<Grid.LayoutTransform>
<TransformGroup>
<RotateTransform Angle="90" />
<MatrixTransform Matrix="-1, 0, 0, 1, 0, 0" />
</TransformGroup>
</Grid.LayoutTransform>
<ContentPresenter/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

Silverlight 5 ListBox IsSelected style binding broken?

i see Silverlight 5 bought style binding. Tried to apply it in a ListBox control, for multiple selection. I have the following XAML ListBox (the code works in a WPF application).
<ListBox ItemsSource="{Binding Values}" SelectionMode="Multiple">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="ListBoxItem">
<TextBlock Text="{Binding DisplayValue}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
When i run this i get a binding error, it seems that it tries to find the IsSelected property on the type of "Values" collection instead of each individual item from that collection. Has anyone else experience this?
Update
Added full code to reproduce, you need to scroll the listbox to see the error in the output log
public class ValueViewModel : INotifyPropertyChanged
{
private bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set
{
_isSelected = value;
OnPropertyChanged("IsSelected");
}
}
private string _displayValue;
public string DisplayValue
{
get { return _displayValue; }
set
{
_displayValue = value;
OnPropertyChanged("DisplayValue");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class MainPageViewModel : INotifyPropertyChanged
{
public ObservableCollection<ValueViewModel> _values;
public ObservableCollection<ValueViewModel> Values
{
get { return _values; }
set
{
_values = value;
OnPropertyChanged("Values");
}
}
public MainPageViewModel()
{
Values = new ObservableCollection<ValueViewModel>();
for (var i = 0; i < 50; i++)
Values.Add(new ValueViewModel() { DisplayValue = i.ToString(), IsSelected = (i % 5) == 0 });
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
And the XAML:
<Grid x:Name="LayoutRoot" Background="White" >
<Grid.Resources>
<viewmodels:MainPageViewModel x:Key="vmMainPage"/>
</Grid.Resources>
<Grid x:Name="workGrid" DataContext="{Binding Source={StaticResource vmMainPage}}">
<ListBox ItemsSource="{Binding Values}" SelectionMode="Multiple" Height="100">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected" Value="{Binding Path=IsSelected, Mode=TwoWay}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="5" Text="{Binding DisplayValue}"/>
<TextBlock Margin="5" Text="{Binding IsSelected}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
Update 2
It seems the problem around the error is that in a scrollable situation if you select items 1 and then scroll down and select item 49 (in the above example), the 1st selection is lost.
I cannot reproduce it. It works fine for me. Here is a full working example based on your code. One issue that I did notice though is that when a ListBoxItem is rendered it automatically sets the property on the data object to false, regardless of whether it was true to begin with. So if you load up a list and set some of it's items to be pre-selected, all the items will be unselected when the ListBoxItems are rendered. One way to prevent this is to use Dispatcher.BeginInvoke and set the selected items there. See my comments in the code below.
XAML:
<UserControl x:Class="SilverlightApplication12.MainPage"
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"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">
<Grid x:Name="LayoutRoot"
Background="White">
<ListBox ItemsSource="{Binding Entities}"
SelectionMode="Multiple">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="IsSelected"
Value="{Binding Path=IsSelected, Mode=TwoWay}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="ListBoxItem">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" />
<TextBlock Margin="10 0 0 0"
Text="IsSelected:" />
<TextBlock Margin="5 0 0 0"
Text="{Binding IsSelected}"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
Code-behind + entity class:
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightApplication12
{
public partial class MainPage : UserControl, INotifyPropertyChanged
{
private ObservableCollection<MyEntity> _Entities;
public ObservableCollection<MyEntity> Entities
{
get { return _Entities; }
set
{
_Entities = value;
OnPropertyChanged("Entities");
}
}
public MainPage()
{
InitializeComponent();
Entities = new ObservableCollection<MyEntity>();
Entities.Add(new MyEntity()
{
Name = "One",
IsSelected = false,
});
Entities.Add(new MyEntity()
{
Name = "Two",
IsSelected = true,
//Even though this is initially true it does not matter.
//When the ListBoxItem is rendered it sets the property to false.
});
Entities.Add(new MyEntity()
{
Name = "Three",
IsSelected = false,
});
LayoutRoot.DataContext = this;
//Enable the following line to set the 2nd item to selected when the page is loaded.
//Dispatcher.BeginInvoke(() => Entities[1].IsSelected = true);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class MyEntity : INotifyPropertyChanged
{
private string _Name;
public string Name
{
get { return _Name; }
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
private bool _IsSelected;
public bool IsSelected
{
get
{
return _IsSelected;
}
set
{
_IsSelected = value;
OnPropertyChanged("IsSelected");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
Everything except this <DataTemplate DataType="ListBoxItem"> looks fine to me.
If the Values collection is a collection of ListBoxItems, you don't need the IsSelected binding.
Otherwise, the DataType on your DataTemplate is wrong and should probably be left blank.
So i've managed to find a workarround that seems to do the job for my needs. It will set the already loaded values once the Loaded event gets triggered. And it wraps the MouseDown event to set the selection status. It's not a true databind but gets the job done, and still keeps the View clean of code.
<ListBox ItemsSource="{Binding Values}" SelectionMode="Multiple" Height="100">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Margin="2" Text="{Binding DisplayValue, Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<ei:ChangePropertyAction
TargetObject="{Binding RelativeSource={RelativeSource AncestorType=ListBoxItem}}"
PropertyName="IsSelected"
Value="{Binding IsSelected}"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeftButtonDown">
<ei:ChangePropertyAction
TargetObject="{Binding}"
PropertyName="IsSelected"
Value="{Binding IsSelected, Converter={StaticResource invertBooleanConverter}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Change TreeViewItem Template when IsSelected and two types using in TreeView

In my TreeView I use two differnt classes for binding. For example, I have a Group what can have ChildGroup and can have Items.
Example code of this classes:
using System.Collections.Generic;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
public class Group
{
public Group(string name)
{
Name = name;
items = new ObservableCollection<Item>();
groups = new ObservableCollection<Group>();
}
public string Name { get;
set;
}
private ObservableCollection<Item> items;
private ObservableCollection<Group> groups;
public ObservableCollection<Item> Items
{
get { return items; }
}
public ObservableCollection<Group> Groups
{
get { return groups; }
}
public IEnumerable<object> AllItems
{
get
{
foreach (var group in groups)
{
yield return group;
}
foreach (var item in items)
{
yield return item;
}
}
}
}
public class Item
{
public Item(string name)
{
ItemName = name;
}
public string ItemName
{
get;
set;
}
}
}
To bind it to TreeView I use following template
<Grid>
<TreeView Name="treeView">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type WpfApplication1:Item}">
<TextBlock Text="{Binding ItemName}" FontStyle="Italic"/>
</DataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
It is easy.
The problem is that I need to change ItemTemplate when Is selected. And I need to change only then Item class selected.
I can do it if only one class use for binding. It also easy using Style and Trigger, like this:
<TreeView Name="treeView1" Grid.Column="1">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}"
x:Key="groupTemplate">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type WpfApplication1:Group}"
ItemsSource="{Binding AllItems}"
x:Key="selectedGroupTemplate">
<TextBlock Text="{Binding Name}" FontStyle="Italic" FontWeight="Bold" FontSize="14"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="HeaderTemplate" Value="{StaticResource groupTemplate}"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="HeaderTemplate" Value="{StaticResource selectedGroupTemplate}"/>
</Trigger>
</Style.Triggers>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
But I have a trouble for multiclass binding.
How can I change SelectedItem template then multiclass binding using? Any ideas?
My code behind sample:
using System.Collections.ObjectModel;
using System.Windows;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window2.xaml
/// </summary>
public partial class Window2 : Window
{
private ObservableCollection<Group> _groups;
public ObservableCollection<Group> Groups
{
get { return _groups; }
}
public Window2()
{
InitializeComponent();
InitGroups();
treeView.ItemsSource = _groups;
treeView1.ItemsSource = _groups;
}
private void InitGroups()
{
_groups = new ObservableCollection<Group>();
Group group1 = new Group("Group1");
group1.Groups.Add(new Group("Group1.1"));
group1.Groups.Add(new Group("Group1.2"));
group1.Groups.Add(new Group("Group1.3"));
group1.Items.Add(new Item("Item1.1"));
group1.Items.Add(new Item("Item1.2"));
group1.Groups[1].Items.Add(new Item("Item1.2.1"));
group1.Groups[1].Items.Add(new Item("Item1.2.2"));
_groups.Add(group1);
Group group2 = new Group("Group2");
group2.Groups.Add(new Group("Group2.1"));
group2.Groups.Add(new Group("Group2.2"));
group2.Items.Add(new Item("Item2.1"));
group2.Groups[0].Items.Add(new Item("Item2.1.1"));
group2.Groups[0].Items.Add(new Item("Item2.1.1"));
_groups.Add(group2);
}
}
}
Result
Now I think to use TreeView.HeaderTemplateSelector, but may be exists way to use only xaml.
Thanks.
There are a number of ways to acheive your desired result. If you are sure that your DataTemplate will only be used in TreeViewItem objects, then the easiest is simply to bind directly to the TreeViewItem.IsSelected property and then react to the change in your DataTemplate:
<DataTemplate DataType="{x:Type WpfApplication1:Item}">
<TextBlock Text="{Binding ItemName}">
<TextBlock.Style>
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsSelected, RelativeSource=
{RelativeSource FindAncestor, AncestorType={x:Type TreeViewItem}}, FallbackValue=False}"
Value="True">
<Setter Property="TextBlock.FontStyle" Value="Italic" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>

Resources