我想为 ListView 中的多个列重用 DataTemplate。鉴于这两个XmlDataProvider
,我通过使用第一个中的选定项目从第二个中选择值。如果我在DataTemplate
. 但这迫使我复制 DataTemplate 的代码并只交换附加资源。我想做的是:
<Window x:Class="LayoutTests.Window2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LayoutTests"
Title="Window2" Height="300" Width="300">
<Window.Resources>
<XmlDataProvider x:Key="XmlDataA" IsInitialLoadEnabled="True">
<x:XData>
<Items xmlns="">
<Item id="1" text="A:1"/>
<Item id="2" text="A:2"/>
<Item id="3" text="A:3"/>
</Items>
</x:XData>
</XmlDataProvider>
<XmlDataProvider x:Key="XmlDataB" IsInitialLoadEnabled="True">
<x:XData>
<Items xmlns="">
<Item id="1" text="B:1"/>
<Item id="2" text="B:2"/>
<Item id="3" text="B:3"/>
</Items>
</x:XData>
</XmlDataProvider>
<local:MultiXmlConverter x:Key="MultiXmlConverter"/>
<local:DatabindingDebugConverter x:Key="DatabindingDebugConverter"/>
<DataTemplate x:Key="Template" >
<TextBlock Text="{Binding Converter={StaticResource MultiXmlConverter}}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<ListView ItemsSource="{Binding Source={StaticResource XmlDataA}, XPath='/Items/Item'}" Background="Transparent">
<ListView.View>
<GridView>
<GridViewColumn CellTemplate="{StaticResource Template}">
<GridViewColumn.DisplayMemberBinding>
<MultiBinding>
<Binding Path="/"/>
<Binding Source="{StaticResource XmlDataB}"/>
</MultiBinding>
</GridViewColumn.DisplayMemberBinding>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
为了完整性(和参考),这里是一个可能的转换器:
public class MultiXmlConverter : IMultiValueConverter
{
public object Convert(object[] value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var element = value[0] as XmlElement;
var dataProvider = value[1] as XmlDataProvider;
XmlNodeList nodes = dataProvider.Document.SelectNodes("/Items/Item/[@id='" + element.Attributes["id"].Value.ToString() + "']");
return nodes[0].Attributes["Text"].Value.ToString();
}
public object[] ConvertBack(object value, Type[] targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new Exception("The method or operation is not implemented.");
}
}
请注意,上面的 XAML 代码将不起作用并产生以下错误:“无法设置 MultiBinding,因为必须指定 MultiValueConverter。”。这MultiBinding
只是我想做的事情的占位符。研究没有发现任何将额外参数传递给 a 的可能性DataTemplate
——但我无法相信如此有用的东西没有隐藏在某个地方。
那么如何将附加资源传递到DataTemplate
旁边的DataContext
?