I'm trying to create a custom expand / collapse indicator for my tree items but there is one situation where it is not working: when the item has no children the indicator is wrong. I'm using the technique suggested in this forum post to fill my tree on demand.
I have tried two different approaches but neither one gives an accurate result.
1. Binding to IsExpanded:
I have created a value converter:
public
class
TreeIconConverter : IValueConverter
{
public
string
ExpandIcon {
get
;
set
; }
public
string
CollapseIcon {
get
;
set
; }
public
string
LeafIcon {
get
;
set
; }
public
object
Convert(
object
value, Type targetType,
object
parameter, CultureInfo culture)
{
if
(value
is
bool
expanded)
return
expanded ? CollapseIcon : ExpandIcon;
return
null
;
}
public
object
ConvertBack(
object
value, Type targetType,
object
parameter, CultureInfo culture)
{
throw
new
NotImplementedException();
}
}
and I'm using a Label as the custom tree indicator:
<
Label
HeightRequest
=
"24"
WidthRequest
=
"24"
HorizontalOptions
=
"Center"
VerticalOptions
=
"Center"
FontFamily
=
"{StaticResource IconFont}"
FontSize
=
"{StaticResource SelectionIconSize}"
Text
=
"{Binding IsExpanded, Converter={StaticResource TreeIconConverter}}"
/>
This gives the best result, but when the item has no children the ExpandIcon is shown.
2. Binding to TreeViewDataItem:
I have altered the value converter to try and detect when the item has children:
public
class
TreeIconConverter : IValueConverter
{
public
string
ExpandIcon {
get
;
set
; }
public
string
CollapseIcon {
get
;
set
; }
public
string
LeafIcon {
get
;
set
; }
public
object
Convert(
object
value, Type targetType,
object
parameter, CultureInfo culture)
{
if
(value
is
TreeViewDataItem item)
{
if
(!item.IsExpanded)
return
CollapseIcon;
if
(item.Item
is
LocationGroup group)
{
if
(group.HaveChildren && group.Children.Count == 0)
return
LeafIcon;
}
return
ExpandIcon;
}
return
null
;
}
public
object
ConvertBack(
object
value, Type targetType,
object
parameter, CultureInfo culture)
{
throw
new
NotImplementedException();
}
}
group.HaveChildren is true only after getting the group's children, if it's false we don't yet have the group's children in memory.
The Label has been changed to:
<Label HeightRequest=
"24"
WidthRequest=
"24"
HorizontalOptions=
"Center"
VerticalOptions=
"Center"
FontFamily=
"{StaticResource IconFont}"
FontSize=
"{StaticResource SelectionIconSize}"
Text=
"{Binding ., Converter={StaticResource TreeIconConverter}}"
/>
With this second version, all the items always show the CollapseIcon.