我想创建一个转换器,在其中我将传递一个类型来查找元素的父层次结构&如果找到这样的类型,它应该返回true,否则为false。
到目前为止,我尝试了下面给出的代码&这是工作。但现在只有我有问题是它找到元素父层次结构,直到元素的父元素为空。我想给祖先级别找到父层次结构中的元素。那么我怎样才能将Ancestor Level赋予转换器?
我使用LayoutHelper.cs Class来查找父层次结构中的元素,如下所示。
public class LayoutHelper
{
public static FrameworkElement FindElement(FrameworkElement treeRoot, Type type, int AncestorLevel)
{
FrameworkElement parentElement = VisualTreeHelper.GetParent(treeRoot) as FrameworkElement;
int level = 1;
while (parentElement != null && level <= AncestorLevel)
{
if (parentElement.GetType() == type)
return parentElement;
else
parentElement = VisualTreeHelper.GetParent(parentElement) as FrameworkElement;
level++;
}
return null;
}
}
IsTypeFoundConverter.cs: -
public class IsTypeFoundConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
FrameworkElement element = value as FrameworkElement;
Type type = parameter as Type;
if (element != null && type != null)
{
element = LayoutHelper.FindElement(element, type,5);
if (element != null)
return true;
}
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
}
带有IsTypeFoundConverter的DataTrigger:
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Self} ,Converter={StaticResource isTypeFoundConverter}, ConverterParameter={x:Type Type_To_Find}}" Value="false">
<!--Setters-->
</DataTrigger>
在这里,在数据触发器中如何将AncestorLevel传递给转换器,这样我才能找到达到该级别的元素?
谢谢, Amol bavannavar
答案 0 :(得分:1)
声明一个包含转换器参数的类型:
public sealed class MyConverterParameter
{
public Type AncestorType { get; set; }
public int AncestorLevel { get; set; }
}
重写转换器以使用此类型:
public sealed class MyConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var myParameter = (MyConverterParameter)parameter;
// other converter stuff here
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
var myParameter = (MyConverterParameter)parameter;
// other converter stuff here
}
}
在XAML中声明其他资源,例如:
<DataTemplate>
<DataTemplate.Resources>
<local:MyConverter x:Key="MyConverterKey"/>
<local:MyConverterParameter x:Key="MyConverterParameterKey" AncestorType="{x:Type Type-To-Find}" AncestorLevel="1"/>
</DataTemplate.Resources>
<!-- DataTemplate tree -->
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path-To-Bind-To, Converter={StaticResource MyConverterKey}, ConverterParameter={StaticResource MyConverterParameterKey}}" Value="Value-To-Fire-Trigger">
<!-- Setters -->
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
P.S。为什么RealtiveSource
的FindAncestor
模式不适合您?