2013-02-16 105 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中搜索它。

我還沒有回答很可能,但希望給你一個主意。