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
297 views
in Technique[技术] by (71.8m points)

c# - Binding datagrid column width

I have two datagrids with one column each. First:

<DataGrid.Columns>
   <DataGridTextColumn x:Name="FilterTextCol01" 
                       IsReadOnly="False" 
                       Width="{Binding ElementName=TextCol01, Path=ActualWidth, Mode=TwoWay}" />
</DataGrid.Columns>

Second:

<DataGridTextColumn CellStyle="{StaticResource DataGridColumnContentLeft}"
                    local:DataGridUtil.Name="TextCol01"
                    x:Name="TextCol01"
                    Header="TextCol01"
                    SortMemberPath="TextCol01"
                    Binding="{Binding TextCol01}" 
                    Width="Auto" 
                    IsReadOnly="True"/>

Binding of the width of first column to the width of the second doesn't work. If I'm doing it in code that way:

FilterTextCol01.Width = TextCol01.ActualWidth;

It works. Could anyone tell me why the first approach doesn't work?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Because DataGrid columns are abstract objects which do not appear in the logical or visual tree of your window. You cannot bind properties on them using ElementName (there will be no namescope which is needed for those bindings).

You can try using Source and x:Reference instead, e.g.

{Binding Source={x:Reference TextCol01}, Path=ActualWidth}

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

...