您可以创建一个 IMultiValueConverter,将 XML 数据和 XPath 表达式转换为新的 XML 数据:
public object Convert(object[] values, Type targetType, object parameter,
CultureInfo culture)
{
try
{
if (values.Length < 2) { return null; }
var data = values[0] as IEnumerable;
if (data == null) { return null; }
var xPathExpression = values[1] as string;
if (xPathExpression == null) { return null; }
XmlDocument xmlDocument = data.Cast<XmlNode>()
.Where(node => node.OwnerDocument != null)
.Select(node => node.OwnerDocument)
.FirstOrDefault();
return (xmlDocument == null) ? null :
xmlDocument.SelectNodes(xPathExpression);
}
catch (Exception) { return null; }
}
public object[] ConvertBack(object value, Type[] targetTypes,
object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
然后,使用 MultiBinding 将 ItemsSource 绑定到 XML 数据和带有转换器的动态 XPathExpression:
<TreeView>
<TreeView.Resources>
<this:XmlXPathConverter x:Key="xmlXPathConverter" />
</TreeView.Resources>
<TreeView.ItemsSource>
<MultiBinding Converter="{StaticResource xmlXPathConverter}">
<Binding Source="{StaticResource dataProvider}" />
<Binding Path="Data.XPathExpression" />
</MultiBinding>
</TreeView.ItemsSource>
</TreeView>