Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
866 views
in Technique[技术] by (71.8m points)

wpf - Binding DataGrid column Header to DataContext

I know this question has been asked before, but none of the "previous" answers seems to work for me...

I have implemented a functionality for multi languages in my application, and I therefor have to bind the header of my DataGrid columns to the DataContext.

I use a dictionary (called Text in the example below) in the DataContext to store the texts, and the binding works fine with textblocks, buttons etc.

<TextBlock Text="{Binding Text[Name], FallbackValue='Name'" />

But, I can't get this to work on the Header-attribute of the DataGrid columns.

I read somewhere, that I need to write a template for the column/header to achieve this, but I can't figure this out either.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You may need to walk back up the tree to get the DataContext you want:

<DataGridTextColumn Binding="{Binding Name}">
    <DataGridTextColumn.HeaderTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding DataContext.Text[Name],
                       RelativeSource={RelativeSource AncestorType=DataGrid}}"/>
        </DataTemplate>
    </DataGridTextColumn.HeaderTemplate>
</DataGridTextColumn>

Doing this directly on the Header property will not work because it cannot be resolved in-place as the column is an abstract object not appearing in the tree.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...