2010-08-30 39 views
0

我對WPF很陌生,我試圖做一些專門的數據綁定。具體來說,我有一個綁定到對象集合的DataGrid,但是我希望列的標題綁定到單獨的對象。你怎麼做到這一點?突破數據綁定層次

我有幾個像這樣定義的類:

public class CurrencyManager : INotifyPropertyChanged 
    { 
     private string primaryCurrencyName; 

     private List<OtherCurrency> otherCurrencies; 

     //I left out the Properties that expose the above 2 fields- they are the standard 
     //I also left out the implementation of INotifyPropertyChanged for brevity 
} 

public class OtherCurrency : INotifyPropertyChanged 
    { 
     private string name; 
     private double baseCurAmt; 
     private double thisCurAmt; 

     //I left out the Properties that expose the above 3 fields- they are the standard 
     //I also left out the implementation of INotifyPropertyChanged for brevity 
} 

然後XAML的重要部分如下所示。假設我已經將頁面綁定到了CurrencyManager類型的特定對象。請注意附加到第二個DataGridTextColumn標題的綁定是不正確的,需要以某種方式訪問​​CurrencyManager對象的屬性PrimaryCurrencyName。也就是說,該列的標題名稱爲「PrimaryCurrencyName」,並且列中的數據仍然綁定到其他貨幣列表的每個元素的屬性ThisCurAmt。

<DataGrid ItemsSource="{Binding Path=OtherCurrencies}" AutoGenerateColumns="False" RowHeaderWidth="0"> 
        <DataGrid.Columns> 
         <DataGridTextColumn Header="Currency Name" Binding="{Binding Path=Name}"/> 
         <DataGridTextColumn Binding="{Binding Path=BaseCurAmt}"> 
          <DataGridTextColumn.Header> 
           <Binding Path="PrimaryCurrencyName"/> 
          </DataGridTextColumn.Header> 
         </DataGridTextColumn> 
         <DataGridTextColumn Header="Amt in this Currency" Binding="{Binding Path=ThisCurAmt}"/> 
        </DataGrid.Columns> 

       </DataGrid> 

我該怎麼做?謝謝!

+0

只是澄清,這是否意味着所有的項目將在第二列中具有相同的值? (也就是說,它們全部等於CurrencyManager的「primaryCurrencyName」? – ASanch 2010-08-30 19:38:52

+0

否。primaryCurrencyName將是頭本身的名稱,而不是列中包含的數據。 – skybluecodeflier 2010-08-30 19:57:59

+0

我明白你的意思了。希望我得到了正確的答案。 – ASanch 2010-08-30 20:09:56

回答

0

問題是,DataGridTextColumn不是可視化樹的一部分。

通常,這可以解決使用DataGridTemplateColumn但在你的情況,我認爲這不會幫助。

很可能this來自Jaime Rodriguez的文章 將帶領你找到一個解決方案(我只看着它很快,但它看起來很合適)。

+0

經過一番努力,我已經成功實現了上面文章中解釋的解決方案。謝謝,HCL! – skybluecodeflier 2010-09-01 00:08:31

0

試試這個:

<DataGridTextColumn Binding="{Binding Path=BaseCurAmt}"> 
    <DataGridTextColumn.Header> 
     <TextBlock> 
      <TextBlock.Text> 
       <Binding Path="DataContext.PrimaryCurrencyName" 
         RelativeSource="{RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGrid}}"/>  
      </TextBlock.Text> 
     </TextBlock> 
    </DataGridTextColumn.Header> 
</DataGridTextColumn> 

基本上,這一次使用的RelativeSource找到DataGrid的DataContext的(這我假設是的CurrencyManager),並顯示其PrimaryCurrencyName財產。希望這可以幫助。