【发布时间】:2018-06-16 15:36:13
【问题描述】:
我正在处理一个嵌套了listbox 的项目。 inner-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
}
请分享您的解决方案,非常感谢您的支持。谢谢。
【问题讨论】:
-
以这种方式嵌套列表框并没有多大意义——我会再看看你想要实现的 UI 的想法表示是什么?通常,树更适合分层数据。
-
@AdamBrown 根据我的用例,我不能使用树来表示数据。因此,嵌套列表框是一种前进的方式。但我在数据绑定方面苦苦挣扎。拜托,你能看看这个吗?
标签: c# wpf xaml data-binding listbox