我正在开发一个嵌套listbox
的项目。内部列表框的ItemsSource
引用其父列表框的ItemsSource中定义的collection of string
。但是当我运行代码时,我无法在嵌套列表框中看到绑定数据。
我搜索了论坛并找到this和this解决方案,但我还无法解决问题。也许代码有问题。所以这是代码的样子:
<ListBox ItemsSource="{Binding Items}" Name="detailList" Margin="5,5,0,0">
<ListBox.ItemTemplate >
<DataTemplate>
<StackPanel Orientation="Vertical" Width="90" Margin="5,0,0,0">
<TextBlock Text="{Binding Name}" Width="60" Height="30" TextWrapping="Wrap" FontSize="11" TextAlignment="Center"/>
<Expander Visibility="{Binding Visibility}" DockPanel.Dock="Top">
<ListBox ItemsSource="{Binding Path=SubFamiliesNames}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Expander>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
代码背后
public ObservableCollection<DirectoryItemViewModel> Items { get; set; }
public DefaultControl()
{
InitializeComponent();
Items = new ObservableCollection<DirectoryItemViewModel>
{
/*Some Initial Data*/
};
this.DataContext = Items;
}
DirectoryItemViewModel.cs
public class DirectoryItemViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
// Constructor
public DirectoryItemViewModel()
{
//initialize some data
_subfamiliesnames = new ObservableCollection<string>();
_subfamiliesnames.Add("File1");
_subfamiliesnames.Add("File2");
_subfamiliesnames.Add("File3");
}
#region Public Properties
public ObservableCollection<string> _subfamiliesnames;
public ObservableCollection<string> SubFamiliesNames
{
get { return _subfamiliesnames; }
set
{
_subfamiliesnames = value;
OnPropertyChanged("SubFamiliesNames");
}
}
// Full path of the directory
public string FullPath { get; set; }
// Item type (Enum)
public DirectoryItemType Type { get; set; }
public string Visibility
{
get
{
return "Visible";
}
}
//The name of the Directory
public string Name { get { return this.Type == DirectoryItemType.Drive ? this.FullPath : DirectoryStructure.GetFileFolderName(FullPath); } }
#endregion
}
请分享您的解决方案,非常感谢您的支持。谢谢。
答案 0 :(得分:1)
在后面的代码中,数据上下文被指定为Items。 因此,对于detailList的ItemSource,它将尝试在Items集合中查找Items的出现。
尝试在后面的代码中指定 this.DataContext = this; 。 然后它会尝试找到&#39; Items&#39;在DefaultControl类中,将能够成功找到它。
如果仍未在列表视图中显示所需数据,请与我联系。