C# 仅将DataTemplate应用于一种类型
我正在尝试将datatemplate仅应用于类型C# 仅将DataTemplate应用于一种类型,c#,wpf,data-binding,listbox,C#,Wpf,Data Binding,Listbox,我正在尝试将datatemplate仅应用于类型体裁。但它也会在搜索(单击)后应用于列表。如何使列表框仅对类型数据应用数据模板 代码隐藏: public class Genre { public string Name { get; set; } public int Count { get; set; } public double Size { get; set; } public string Drive { get; set; } } privat
体裁
。但它也会在搜索(单击
)后应用于列表
。如何使列表框
仅对类型
数据应用数据模板
代码隐藏:
public class Genre
{
public string Name { get; set; }
public int Count { get; set; }
public double Size { get; set; }
public string Drive { get; set; }
}
private void Search_Click(object sender, RoutedEventArgs e)
{
var path = Constants.allMoviesPath;
var ext = new List<string> { @".txt", @".ini", @".exe", @".mob", @".srt", @".ass" };
lstBox.ItemsSource = Directory.GetFiles(path, "*" + SearchString + "*", SearchOption.AllDirectories)
.Where(f => !ext.Contains(System.IO.Path.GetExtension(f)))
.Select(f => System.IO.Path.GetFileNameWithoutExtension(f))
.ToList();
}
private void btnStats_Click(object sender, RoutedEventArgs e)
{
lstBox.ItemsSource = FileLists.MoviesCountSizeStats();
}
不要像现在这样将模板应用于列表框中的所有项目,而是使用隐式键(即,
TargetType
)将模板作为资源添加到ListBox.Resources
(或其他合适的资源字典)中,并自动为项目类型选择模板:
您可以根据需要为列表框中可能出现的其他数据类型添加其他模板。我认为从中删除ItemTemplate属性并将模板定义放入其中应该可以做到这一点
<ListBox
x:Name="lstBox"
Background="CadetBlue"
FontFamily="Consolas"
FontSize="14"
FontWeight="DemiBold"
ItemContainerStyle="{DynamicResource _ListBoxItemStyle}"
ItemTemplate="{StaticResource genreTemplate}"
MouseDoubleClick="lstBox_MouseDoubleClick" />