简体   繁体   中英

How to select WPF TreeViewItem which has been populated using XmlDataProvider?

I have a WPF TreeView which has been populated from an XML file at runtime. I click on a button and a FileDialog box appears and then I select an XML file. Then the XML file is loaded in the TreeView . I have used a XmlDataProvider and some HierarchicalDataTemplate s to load the XML.

I have added an action handler with the TreeView, but when I select an item of that TreeView I can't find any reference of that item. I only find the reference of the first element.

How can I solve this issue?

The XAML is:

<Window x:Class="Demo2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="600" Width="800">
<Window.Resources>
    <XmlDataProvider x:Key="MEIInformation" XPath="/MEI" />
    <HierarchicalDataTemplate DataType="Case" ItemsSource="{Binding}">
        <TextBlock Text="{Binding XPath=@Name}"></TextBlock>            
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="Phase" ItemsSource="{Binding}">
        <TextBlock Text="{Binding XPath=@Name}"></TextBlock>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="Trigger" ItemsSource="{Binding}">
        <TextBlock Text="{Binding XPath=@Name}"></TextBlock>
    </HierarchicalDataTemplate>
</Window.Resources>  
<Grid>
    <ToolBarTray>
        <ToolBar>                
            <Button ToolTip="Open Test Suite" Click="OpenTestSuite">
                <Image Source="Icons/open.png"></Image>
            </Button>                
        </ToolBar>
    </ToolBarTray>
    <TreeView x:Name="trv" FontSize="14" Height="518" HorizontalAlignment="Left" Margin="6,31,0,0"  VerticalAlignment="Top" Width="431">
        <TreeViewItem ItemsSource="{Binding Source={StaticResource MEIInformation}, XPath=*}" Header="Suites"></TreeViewItem>
    </TreeView>                           
</Grid>
</Window>

And the code snippest is:

public partial class MainWindow : Window
{     
    public MainWindow()
    {
        InitializeComponent();     
        this.trv.MouseRightButtonUp+=new MouseButtonEventHandler(DoSomething);      
    }    

    private void OpenTestSuite(object sender, RoutedEventArgs e)
    {
        XmlDocument xmlDocument = new XmlDocument();
        OpenFileDialog open = new OpenFileDialog();
        open.Filter = "XML Files (*.xml)|*.xml";
        if (open.ShowDialog() == true)
        {
            xmlDocument.Load(open.FileName);
            XmlDataProvider dataProvider = this.FindResource("MEIInformation") as XmlDataProvider;
            dataProvider.Document = xmlDocument;         
        }
    }        

    private void DoSomething(object sender, MouseEventArgs e)
    {
        MessageBox.Show("Do Something in TreeView!");
        TreeViewItem childItem = e.Source as TreeViewItem;
        if (childItem != null)
        {
            MessageBox.Show(childItem.Header.ToString()); // or MessageBox.Show(childItem.toString);
            childItem.IsSelected = true;
        }
        else
            MessageBox.Show("No Selected Item!");                    
    }                
}

XML

<?xml version="1.0" encoding="ISO-8859-1"?>
<MEI>
    <Case Name="Jean Price">
        <Phase Name="January">
            <Trigger Name="Order # JAN001"></Trigger>
            <Trigger Name="Order # JAN002"></Trigger>
        </Phase>
        <Phase Name="February">
            <Trigger Name="Order # FEB001"></Trigger>
        </Phase>
    </Case>
    <Case Name="John P Grant">
        <Phase Name="April">
            <Trigger Name="Order # APR001"></Trigger>
    <!-- ... -->
</MEI>

I just want to have a reference of that item so that i can add new item after that item.


@Mart I have changed the treeview on the xaml like this... (added SelectedItemChanged="DoSomething")...

<TreeView SelectedItemChanged="DoSomething"....../>    

And the c# code is now.......

private void DoSomething(object sender, EventArgs e)
        {
            MessageBox.Show("Do Something in TreeView!");           

            TreeViewItem childItem = sender as TreeViewItem;                        
            if (childItem != null)
            {
                MessageBox.Show(childItem.Header.ToString());
                childItem.IsSelected = true;
                MessageBox.Show("It Works!");
            }
            else
                MessageBox.Show("No Selected Item!");                    
        }     

but there is no luck at all. And i have not understood ur UIElement sugestion...:(

This is the way I found to get the selectedTreeViewItem value, I got it from xmlElement .

Considering this xaml code:

<i>
<Window.Resources>
    <HierarchicalDataTemplate DataType="Filial"
                              ItemsSource="{Binding XPath=./*}">
        <StackPanel Orientation="Horizontal">
            <Image Source="/WpfClient;component/Images/image4.png"
                   Height="20"></Image>
            <TextBlock Margin="5,0,0,0"
                       Text="{Binding XPath=@name}"
                       FontSize="18"
                       FontFamily="BankGothic Md BT"
                       Foreground="#FF355CE5"/>
        </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="Setor"
                              ItemsSource="{Binding XPath=./*}">
        <StackPanel Orientation="Horizontal">
            <TextBlock Margin="5,0,0,0"
                       Text="{Binding XPath=@name}"
                       FontWeight="Bold" />
        </StackPanel>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate DataType="User">
        <StackPanel Orientation="Horizontal">
            <Image Source="{Binding XPath=@source}"
                   Height="15"></Image>
                <TextBlock Margin="5,0,0,0"
                       Text="{Binding XPath=@name}"
                       FontStyle="Italic" />
        </StackPanel>
    </HierarchicalDataTemplate>
    <XmlDataProvider x:Key="xmlDP"
                     Source="Contatos.xml"
                     XPath="/Contatos/Filial"></XmlDataProvider>
</Window.Resources>
<Grid Width="Auto"
      Height="Auto">
    <TreeView Name="tv"
              ItemsSource="{Binding }"
              DataContext="{StaticResource xmlDP}"
              Margin="0,0,0,0"
              TreeViewItem.Selected="tv_Selected">
        <TreeView.ItemContainerStyle>
            <Style TargetType="TreeViewItem">
                <Setter Property="TreeViewItem.IsExpanded"
                        Value="True" />
            </Style>
        </TreeView.ItemContainerStyle>
    </TreeView>
</Grid>
</i> </pre>

and this c# codebehind:

private void tv_Selected(object sender, RoutedEventArgs e)
    {
        System.Xml.XmlElement xmlElement= (XmlElement)tv.SelectedItem;

        string mySelectedValue = xmlElement.Attributes[0].Value.ToString();
        MessageBox.Show(mySelectedValue , "SelectedTreeValue", MessageBoxButton.OK, MessageBoxImage.Information);
    }
    </i>

and this is the xml file:

<i>
<?xml version="1.0" encoding="utf-8" ?>
  <Contatos>
    <Filial name="Firm">
      <Setor name="Sector 1">
        <User name="user1" source="/WpfClient;component/Images/user.png"></User>
        <User name="user2" source="/WpfClient;component/Images/user.png"></User>
        <User name="user3" source="/WpfClient;component/Images/admin.png"></User>
      </Setor>
     <Setor name="Sector40">
        <User name="user43" source="/WpfClient;component/Images/admin.png"></User>
        <User name="user44" source="/WpfClient;component/Images/user.png"></User>
        <User name="user45" source="/WpfClient;component/Images/user.png"></User>
        <User name="user46" source="/WpfClient;component/Images/user.png"></User>
     </Setor>
   </Filial>
</Contatos>
</i>

I can not see what fires you DoSomething handler, I guess it responds to a Click event.

If it is a Click on an element of the item template, you may not get the correct sender parameter.

You can cast the sender to an UIElement and then access its DataContext which should be one of your XML element.

The other way is to react to the treeview's SelectionChanged event, that will give you the treview item in the event arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM