【问题标题】:How to bind XML to a TreeView without code behind for (MVVM, dataContext from XAML)如何在没有代码的情况下将 XML 绑定到 TreeView(MVVM,来自 XAML 的 dataContext)
【发布时间】:2010-12-14 20:16:37
【问题描述】:

我有一个窗口,里面有一个树视图控件和一个 XML 文件。我想完全从 XAML 将树视图绑定到 XML 文件,而不需要任何 C# 代码。

这就是我现在的做法:

XAML

<Window.Resources>
    <HierarchicalDataTemplate ItemsSource="{Binding Path=Elements}" x:Key="TreeViewItemData">
        <TreeViewItem Header="{Binding Path=Attribute[text].Value}" IsExpanded="True"/>
    </HierarchicalDataTemplate>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="40" />
        <RowDefinition Height="370*" />
    </Grid.RowDefinitions>
    <TextBlock Text="RD Admin Tool" Grid.Row="0" FontSize="22" FontWeight="Bold" Padding="50,5"></TextBlock>
    <StackPanel Orientation="Horizontal" Grid.Row ="1">
        <Border BorderBrush="#FF7C7B7B" BorderThickness="1" Name="tBorder" Width="200" CornerRadius="5" Background="#FFF5F2F2">
            <TreeView Name="OptionsTree" 
                      ItemsSource="{Binding Path=Root.Elements}" 
                      ItemTemplate="{StaticResource TreeViewItemData}" 
                      HorizontalAlignment="Left" VerticalAlignment="Top" 
                      Margin="5,0,0,0" FontSize="18" Background="#FFF5F2F2">
            </TreeView>
        </Border>
        <Canvas Name="OptionContent" Width="445">
        </Canvas>
    </StackPanel>
</Grid>

后面代码中的构造函数

 public MyWindow()
    {
        InitializeComponent();

        XDocument doc = XDocument.Parse(File.ReadAllText(@"C:\Tree.xml"));
        this.MyTreeView.DataContext = doc;
    }

但我真的很想从 XAML 编写它并且没有代码。

有什么建议吗?

【问题讨论】:

    标签: .net wpf data-binding mvvm treeview


    【解决方案1】:

    您可以使用 XAML 中的 XmlDataProvider 将您的外部 XML 定义为资源。然后可以在 XAML 中的各种元素中引用并绑定它。

    可以在 here 找到演练...此外,MSDN 示例使用了 XmlDataProviderTreeView here

    【讨论】:

    • @Stuart 我们至少有不同的链接...一切都没有白费...:)
    • 伙计们,感谢您的反馈,但我正试图让它与 TreeView 一起工作,它显示为空(无节点)。你能放一些代码示例吗?再次感谢
    • @Michel 添加了另一个链接到使用 MSDN 上的 XmlDataProvider 和 TreeView 的示例
    【解决方案2】:

    您可以使用 XmlDataProvider 指定 xml 数据源,然后绑定到该数据源。

    本文讨论该技术:http://msdn.microsoft.com/en-us/magazine/cc163299.aspx

    【讨论】:

      猜你喜欢
      • 2018-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-08
      相关资源
      最近更新 更多