简体   繁体   English

如何使用 XmlDataProvider 填充的 select WPF TreeViewItem?

[英]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.我有一个 WPF TreeView已在运行时从 XML 文件填充。 I click on a button and a FileDialog box appears and then I select an XML file.我单击一个按钮并出现一个FileDialog框,然后我 select 一个 XML 文件。 Then the XML file is loaded in the TreeView .然后 XML 文件被加载到TreeView中。 I have used a XmlDataProvider and some HierarchicalDataTemplate s to load the XML.我使用了XmlDataProvider和一些HierarchicalDataTemplate来加载 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.我已经用 TreeView 添加了一个动作处理程序,但是当我 select 的一个项目时,我找不到该项目的任何参考。 I only find the reference of the first element.我只找到第一个元素的引用。

How can I solve this issue?我该如何解决这个问题?

The XAML is: XAML 是:

<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

<?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")... @Mart我已经像这样更改了xaml上的treeview ...(添加了SelectedItemChanged =“DoSomething”)...

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

And the c# code is now.......现在 c# 代码.......

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...:(而且我还没有理解你的 UIElement 建议...... :(

This is the way I found to get the selectedTreeViewItem value, I got it from xmlElement .这是我发现获取selectedTreeViewItem值的方式,我从xmlElement得到它。

Considering this xaml code:考虑到这个 xaml 代码:

<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:这个 c# 代码隐藏:

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:这是 xml 文件:

<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.我看不出是什么触发了DoSomething处理程序,我猜它响应了Click事件。

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.您可以将发送者转换为UIElement ,然后访问它的DataContext ,它应该是您的 XML 元素之一。

The other way is to react to the treeview's SelectionChanged event, that will give you the treview item in the event arguments.另一种方法是对树视图的SelectionChanged事件做出反应,这将为您提供事件 arguments 中的查看项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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