I\'m writing a custom ItemsControl
(a tabbed document container), where each item (tab) can remove itself from the UI when the user closes it. However, I can\'t
OK, I found a solution...
If the ItemsSource
is databound, I either raise an event (for use with code-behind) or invoke a command (for use with a ViewModel) to remove the item from the ItemsSource
collection.
If it's not databound, I raise an event to prompt the user for confirmation, and I remove the container directly from Items
public static readonly DependencyProperty CloseTabCommandProperty =
DependencyProperty.Register(
"CloseTabCommand",
typeof(ICommand),
typeof(TabDocumentContainer),
new UIPropertyMetadata(null));
public ICommand CloseTabCommand
{
get { return (ICommand)GetValue(CloseTabCommandProperty); }
set { SetValue(CloseTabCommandProperty, value); }
}
public event EventHandler RequestCloseTab;
public event EventHandler TabClosing;
internal void CloseTab(TabDocumentContainerItem tabDocumentContainerItem)
{
if (ItemsSource != null) // Databound
{
object item = ItemContainerGenerator.ItemFromContainer(tabDocumentContainerItem);
if (item == null || item == DependencyProperty.UnsetValue)
{
return;
}
if (RequestCloseTab != null)
{
var args = new RequestCloseTabEventArgs(item);
RequestCloseTab(this, args);
}
else if (CloseTabCommand != null)
{
if (CloseTabCommand.CanExecute(item))
{
CloseTabCommand.Execute(item);
}
}
}
else // Not databound
{
if (TabClosing != null)
{
var args = new TabClosingEventArgs(tabDocumentContainerItem);
TabClosing(this, args);
if (args.Cancel)
return;
}
Items.Remove(tabDocumentContainerItem);
}
}