How to get the ListBoxItem's default Item/Content/DataTemplate?
I wanted to use the ListBox's default ItemTemplate/DataTemplate/ContentTemplate or whatever it is to reduce some code of my ComboBox like Custom FrameworkElement:
In the Popup I've a ListBox named list and when I select an item from the list it's displayed in a ContentControl named selectedContent. To set the content style of the list as well as selectedContent I've two normal properties, DisplayPath and ItemTemplate:
string display;
public string DisplayPath {
get { return display; }
set {
display =
list.DisplayMemberPath = value;
selectedContent.SetBinding(ContentControl.ContentProperty, new Binding() {
Path = new PropertyPath($"{nameof(list.SelectedItem)}.{DisplayPath}"),
Source = list
});
}
}
DataTemplate itemTemplate;
public DataTemplate ItemTemplate {
get { return itemTemplate; }
set {
itemTemplate =
list.ItemTemplate =
selectedContent.ContentTemplate = value;
selectedContent.SetBinding(ContentControl.ContentProperty, new Binding() {
Path = new PropertyPath(nameof(list.SelectedItem)),
Source = list
});
}
}
and in both of these I'm binding the ContentControl.ContentProperty in two different ways. I wanted to move the binding part in the Loaded handler to make those auto properties look like this:
string display;
public string DisplayPath {
get { return display; }
set { display = list.DisplayMemberPath = value; }
}
DataTemplate itemTemplate;
public DataTemplate ItemTemplate {
get { return itemTemplate; }
set { itemTemplate = list.ItemTemplate = value }
}
and the Loaded handler onLoaded like this:
void onLoaded(object sender, RoutedEventArgs e) {
selectedContent.ContentTemplate = list.WhateverTemplateItGets;
selectedContent.SetBinding(ContentControl.ContentProperty, new Binding() {
Path = new PropertyPath(nameof(list.SelectedItem)),
Source = list
});
}
BUT I don't know yet what template is being used by the list so in the onLoaded I currently have to have these to make it work:
void onLoaded(object sender, RoutedEventArgs e) {
var binding = new Binding() { Source = list };
if (ItemTemplate != null) {
selectedContent.ContentTemplate = list.ItemTemplate;
binding.Path = new PropertyPath(nameof(list.SelectedItem));
}
else binding.Path = new PropertyPath($"{nameof(list.SelectedItem)}.{DisplayPath}");
selectedContent.SetBinding(ContentControl.ContentProperty, binding);
}
can it be simplified by using the default template list is using?