c# - 如何确定从 ItemsControl 派生的类中的项目类型
问题描述
我正在为 ItemsControl 实现一个附加属性。面对这样一个我无法解决的任务。我从 ItemTemplate 中的 UI 元素沿着可视化树爬到 ItemsControl。没有问题。但我还需要在 ItemsControl 中定义用于生成项目的类型。而且这个类型在ItemsControl派生的不同类中也有所不同。
假设 ListBox 可以应用以下代码
public static bool GetIndexOn(FrameworkElement element)
{
int? index = (int?)element.GetValue(IndexProperty);
if (index == null)
{
FrameworkElement parent = element;
// Search ListBoxItem
// But I need to find any type used to generate Item
while (!(parent is System.Windows.Controls.ListBoxItem || parent == null))
parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
if (parent == null)
return false;
// Saving the ListBoxItem
System.Windows.Controls.ListBoxItem listBoxItem = (System.Windows.Controls.ListBoxItem)parent;
// Search ItemsControl
while (!(parent is ItemsControl || parent == null))
parent = VisualTreeHelper.GetParent(parent) as FrameworkElement;
if (parent == null)
return false;
// Saving the ListBox
ItemsControl listBox = (ItemsControl)parent;
// Retrieving and storing index of ListBoxItem in ListBox
index = listBox.ItemContainerGenerator.IndexFromContainer(listBoxItem);
element.SetValue(IndexPropertyKey, index);
}
return false;
}
解决方案
推荐阅读
- python - 在 Python 中打印一个类中包含的所有元素
- django - 如何从 django 应用程序视图中的模块访问自定义装饰器
- database - 链接和集线器之间的 Data Vault 关系
- cordova-plugins - “CordovaPlugins”类型上不存在属性“MediaScannerPlugin”
- excel - 从 VLOOKUP 函数中删除找到的结果行
- sql-server - DBATools 错误:'无法加载文件或程序集'Microsoft.SqlServer.Replication.dll 或其依赖项之一''
- node.js - 对于产生节点子进程的 Electron 应用程序,子进程没有获得全磁盘访问权限
- python - 如何通过提供值作为条件来获取字典键
- javascript - Javascript:搜索对象数组并从对象中获取链接值
- python - Pyspark:依靠 pyspark.sql.dataframe.DataFrame 需要很长时间