我不明白爲什麼我的DataContext綁定不起作用,當我運行我的應用程序。我也使用設計時數據上下文,它的工作原理。爲什麼WPF XAML DataContext綁定不起作用?
這裏是我的XAML的主要部分。這是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">
這也是從MainWindow.xaml
<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>
這是主要的TreeView。我需要在這裏顯示一切。
<TreeView DataContext="{Binding}" ItemsSource="{Binding Items}" x:Name="TreeView" Grid.Row="1" VerticalContentAlignment="Top" Margin="10,5" ItemTemplate="{StaticResource RootDataTemplate}">
</TreeView>
這裏是C#代碼。這是MainWindow.xaml.cs,命名空間是Logs_Cleaner_WPF
public partial class MainWindow : Window
{
public static ObservableCollection<DisplayItem> Items { get; set; }
}
DisplayItem:
public abstract class DisplayItem : INotifyPropertyChanged
{
private string _path;
public virtual string Path
{
get { return _path; }
set
{
_path = value;
OnPropertyChanged();
}
}
private long _size;
public long Size {
get { return _size; }
set
{
_size = value;
OnPropertyChanged();
}
}
private bool _checked;
public bool Checked
{
get { return _checked; }
set
{
_checked = value;
OnPropertyChanged();
}
}
public override string ToString()
{
return Path;
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
如何使用數據填充Items集合? –
private void OnLoaded(object sender,RoutedEventArgs routedEventArgs) { _dirHelper = App.UnityContainer.Resolve(); JustForTest(); } private void JustForTest() { Items = new ObservableCollection (); Items.Add(new DisplayFolder {Checked = true,Path =「MyPath7」}); } –
Maksym
你可能會發現[這個關於DataContext的回答](http://stackoverflow.com/a/7262322/302677)對於通讀有用:) – Rachel