代码之家  ›  专栏  ›  技术社区  ›  skybluecodeflier

打破数据绑定层次结构

  •  0
  • skybluecodeflier  · 技术社区  · 14 年前

    我对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”,对于其他货币列表的每个元素,列中的数据仍然绑定到属性thiscurramt。

    <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>
    

    我该怎么做?谢谢!

    2 回复  |  直到 14 年前
        1
  •  0
  •   HCL    14 年前

    问题是,DataGridTextColumn不是可视树的一部分。

    正常情况下,可以使用 DataGridTemplateColumn 但在你的情况下,我认为这不会有帮助。

    可能 this Jaime Rodriguez的文章 将引导您找到一个解决方案(我只是快速地看了一下,但看起来很合适)。

        2
  •  0
  •   ASanch    14 年前

    试试这个:

    <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查找数据报的dataContext(我假设它是currencyManager)并显示其primarycurrencyname属性。希望这有帮助。