How would I clear the TreeView selection within a WPF TreeView? I have tried looping through the TreeNodes
and clearing the IsSelected
property, however that is a ReadOnly
property. Any ideas?
The TreeView
is using XML Binding through the XMLDataProvider
object.
I came across the exact same problems and wrote the following code which will work on any treeview, with just a single line call to the first function.
class TomWrightsUtils
{
public static void ClearTreeViewSelection(TreeView tv)
{
if (tv != null)
ClearTreeViewItemsControlSelection(tv.Items, tv.ItemContainerGenerator);
}
private static void ClearTreeViewItemsControlSelection(ItemCollection ic, ItemContainerGenerator icg)
{
if ((ic != null) && (icg != null))
for (int i = 0; i < ic.Count; i++)
{
TreeViewItem tvi = icg.ContainerFromIndex(i) as TreeViewItem;
if (tvi != null)
{
ClearTreeViewItemsControlSelection(tvi.Items, tvi.ItemContainerGenerator);
tvi.IsSelected = false;
}
}
}
}
Not sure what you mean by TreeNodes.
Typically you would have a corresponding IsSelected
property on your view model that your view binds to:
<TreeView>
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</TreeView.ItemContainerStyle>
</TreeView>
Therefore, you would just loop through the data items in your view model and set IsSelected = false
there.
However, it sounds like you don't have such a property. That being the case, you need to get the corresponding TreeViewItem
for each data item. See the TreeView.ItemContainerGenerator
property for info on how to do this. Something like:
var treeViewItem = _treeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
treeViewItem.IsSelected = false;
TreeViewItem tvi = tvMain.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;
if (tvi != null) { tvi.IsSelected = true; tvi.IsSelected = false; }
Find the selected item and set the value:
private void Button_Click(object sender, RoutedEventArgs e)
{
TreeViewItem tvi = treeviewExample.SelectedItem as TreeViewItem;
if (tvi != null)
{
tvi.IsSelected = false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With