2013-02-16 101 views
0

我有一个使用ContentTemplate进行样式设置的ContentControl窗口。列表框中的WPF(XAML)绑定项目模板

ContentTemplate包含嵌套在Grid内的简单ListBox。 Grid使用代码设置DataContext属性集(绑定到CollectionViewSource - 让我们称之为cvs1)。列表框ItemsSource继承自网格,列表框项目的人口工作正常。例如

<Grid x:Name="Grid1"> 
    <ListBox x:Name="ListBox1" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"/> 
</Grid> 

ListBox正在设计样式中,主样式存储在ResourceDictionary中。

我使用ItemTemplate设置列表框的样式值,但我还希望使用DataTrigger来动态应用不同的Setter。我面临的挑战是我似乎无法将DataTrigger中的Binding建立到单独的CollectionViewSource(我们称之为cvs2)。

<Style TargetType="{x:Type ListBox}"> 
    <Style.Triggers> 
     <!-- This seems to be trying to bind to cvs1, the error is it can't find the property --> 
     <DataTrigger Binding="{Binding cvs2, Path=TemplateName}" Value="ABC"> 
      <Setter Property="ItemTemplate"> 
     </DataTrigger> 

     <!-- This just doesn't seem to work --> 
     <DataTrigger Binding="{Binding Source={StaticResource cvs2},Path=TemplateName}" Value="XYZ"> 
      <Setter Property="ItemTemplate"> 
     </DataTrigger> 
    </Style.Triggers> 
</Style> 

cvs1和cvs2都在ResourceDictionary中定义。

<CollectionViewSource x:Key="cvs1" /> 
<CollectionViewSource x:Key="cvs2" /> 

然后为引用如下:

<ResourceDictionary.MergedDictionaries> 
    <ResourceDictionary Source="DataSources.xaml" /> 
</ResourceDictionary.MergedDictionaries> 

这个问题我似乎面对的是ItemTemplate从列表框继承的DataContext,我似乎无法克服这个问题,建立绑定到cvs2数据源。我认为这将是一个相当常规的StaticResource绑定任务。似乎并非如此。

我已经测试了下面的代码在网格外的标签(在主窗口)来调试数据:

<Label Content="{Binding cvs2, Path=/TemplateName}"/> 

该工程中,标签被填充有TEMPLATENAME的值。

但是,如果我在ItemsTemplate内的DataTrigger上使用此项,则绑定不成立。

如何从ItemTemplate内建立对cvs2的绑定?

回答

0

我是silverlight开发人员,我只是使用转换器绑定来实现这些类型的目标。

但我喜欢Xaml,根据你的xaml的理解,根据你的cvs2对象的TemplateName属性,你想改变ItemTemplate,不是吗?

如果是这样,为什么你不给我们价值ItemTemplate属性?

 <DataTrigger Binding="{Binding Source={StaticResource cvs2}, 
        Path=TemplateName}" Value="XYZ"> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <TextBlock Text={Binding}/> 
      <Setter.Value> 
     </Setter> 
    </DataTrigger> 
    // When cvs2.TemplateName=XYZ use this template, isn't it? 

在此资源之前,cvs2是否首先作为资源加载?

输出是否有任何绑定错误?

您可以尝试给出特定的样式,而不是由x:Key隐含。

价值转换器可能会帮助你。

如果您使用StaticResource,它会从关键字按层次结构自上而下地查找,所以我不认为它从ListBox的datacontext中搜索它。

我还没有回答很可能,但希望给你一个主意。