我在XAML中绑定了一个对象的实例。它有一个方法可以返回给我一个其他对象的列表(基于我传递此方法的属性值,它将返回具有该属性值的所有对象)。
<ObjectDataProvider ObjectInstance="_this.DataContext" MethodName="GetListByCategory" x:Key="List">
<ObjectDataProvider.MethodParameters>
<System:String>Windows</System:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
我(最终)想要在带有一些复杂的DataTemplate的选项卡上显示此列表。但不要超越自己。
我希望获得应该在TabControl中的特定TabItem上显示的所有对象(具有与TabItem的名称或标题匹配的类别的对象 - 这在方法中完成)。如何将绑定方法传递给相关的TabItem的标题或名称?
请记住,我需要绑定到此绑定方法的返回值,以在TabItem中的DataTemplate中显示。我不知道这是否与问题的答案有关,但我想确保我清楚地定义它。
答案 0 :(得分:3)
不幸的是,MethodParameters
的{{1}}无法直接绑定。
您可以使用ObjectDataProvider
或TwoWay
绑定来解决此问题。以下是使用OneWayToSource
替代Directory.GetFiles
方法的示例:
GetListByCategory
使用OneWayToSource将<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
xmlns:io="clr-namespace:System.IO;assembly=mscorlib"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid.Resources>
<x:Array x:Key="directories" Type="{x:Type sys:String}">
<sys:String>C:\</sys:String>
<sys:String>C:\Windows\</sys:String>
<sys:String>C:\Windows\System32\</sys:String>
</x:Array>
<ObjectDataProvider x:Key="fileList" ObjectType="{x:Type io:Directory}" MethodName="GetFiles">
<ObjectDataProvider.MethodParameters>
<!-- Initial value, this will get wiped out by the Binding below. -->
<sys:String>C:\</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Grid.Resources>
<TabControl ItemsSource="{StaticResource directories}">
<TabControl.ItemContainerStyle>
<Style TargetType="{x:Type TabItem}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate DataType="{x:Type sys:String}">
<ListBox ItemsSource="{Binding Source={StaticResource fileList}}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</TabControl.ItemContainerStyle>
<TabControl.SelectedItem>
<Binding Source="{StaticResource fileList}"
Path="MethodParameters[0]"
BindsDirectlyToSource="True"
Mode="OneWayToSource"/>
</TabControl.SelectedItem>
</TabControl>
</Grid>
绑定到TabControl.SelectedItem
,这样当我们更改选项卡时,方法参数将更改为新目录。