2010-08-30 56 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财产。希望这可以帮助。