为什么WPF XAML DataContext绑定不起作用?

时间:2016-01-06 14:44:50

标签: c# wpf xaml

我无法理解为什么运行我的应用程序时我的DataContext绑定不起作用。我也在使用设计时datacontext,它可以工作。

以下是我的XAML的主要部分。这是来自MainWindow.xaml

npm install tsd@next -g
tsd install jquery -ors

这也来自MainWindow.xaml

<Window x:Class="Logs_Cleaner_WPF.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" MinWidth="800" MinHeight="600" WindowStartupLocation="CenterScreen"
    xmlns:data="clr-namespace:Logs_Cleaner_WPF.Data"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    DataContext="{Binding Items, RelativeSource={RelativeSource Self}}"
    d:DataContext="{Binding Source={d:DesignInstance Type=data:DesignData, IsDesignTimeCreatable=True}}"
    mc:Ignorable="d">

这是主要的TreeView。我需要在这里展示一切。

<Window.Resources>
    <HierarchicalDataTemplate x:Key="ChildDataTemplate">
        <TextBlock Text="{Binding Path}"></TextBlock>
    </HierarchicalDataTemplate>
    <HierarchicalDataTemplate x:Key="RootDataTemplate" ItemsSource="{Binding DisplayFolders}" ItemTemplate="{StaticResource ChildDataTemplate}">
        <TextBlock Text="{Binding Path}"></TextBlock>
    </HierarchicalDataTemplate>
</Window.Resources>

这是C#代码。这是来自MainWindow.xaml.cs,命名空间是Logs_Cleaner_WPF

<TreeView DataContext="{Binding}" ItemsSource="{Binding Items}"     x:Name="TreeView" Grid.Row="1" VerticalContentAlignment="Top" Margin="10,5" ItemTemplate="{StaticResource RootDataTemplate}">
    </TreeView>

DisplayItem:

public partial class MainWindow : Window
{
    public static ObservableCollection<DisplayItem> Items { get; set; }
}

2 个答案:

答案 0 :(得分:2)

由于之前的声明,您的DataContext已经Items收集了!

DataContext="{Binding Items, RelativeSource={RelativeSource Self}}"

因此绑定到ItemsSource应该只是{Binding }

<TreeView ItemsSource="{Binding }" x:Name="TreeView" ... />

在你的情况下它又是{Binding Items},所以它试图绑定到Items.Items,这是不存在的。

答案 1 :(得分:-2)

我认为最好以适当的方式重写它,就像@NETscape建议的那样。我要实现MVVM。