Answered by:
Text Box in GridViewColumn. Can I bind it's width to the width of the containing Column?

Question
-
I have a data template which allows me to put a text box into columns of a ListView, ultimately GridViewColumns:
<DataTemplate x:Key="myTemplate">
<TextBox Name="myTextBox"
Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type GridViewColumn}},Path=ActualWidth}"/>
</DataTemplate>
In the XAML for the GridViewColumn:
<GridViewColumn Header="Header 1"
CellTemplate="{StaticResource myTemplate}"
The text box shows up ok, but what I want is for the width of it to match whatever the width of the column that contains it is. I thought that the binding above might work, but it doesn't. My trace errors show:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.GridViewColumn', AncestorLevel='1''. BindingExpression:Path=ActualWidth; DataItem=null; target element is 'TextBox' (Name='myTextBox'); target property is 'Width' (type 'Double')
Thanks,
HedleyTuesday, April 14, 2009 10:35 PM
Answers
-
As GridViewColumn don't render as a visual in the VisualTree, try to use ListViewItem instead:
<TextBox Name="myTextBox" Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListViewItem}},Path=ActualWidth}"/>- Marked as answer by Hedley Sohn Wednesday, April 15, 2009 3:36 PM
Tuesday, April 14, 2009 11:22 PM
All replies
-
As GridViewColumn don't render as a visual in the VisualTree, try to use ListViewItem instead:
<TextBox Name="myTextBox" Width="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListViewItem}},Path=ActualWidth}"/>- Marked as answer by Hedley Sohn Wednesday, April 15, 2009 3:36 PM
Tuesday, April 14, 2009 11:22 PM -
Hi
You can try this style to stretch the content of column.
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
Hope this helps.
Yiling, MVP(Visual C++)- Proposed as answer by BrianNoyes2 Thursday, July 2, 2009 6:09 PM
Wednesday, April 15, 2009 12:44 AM -
That was indeed the issue with the binding. Changing to ListViewItem resolved the problem.
Now however, I am seeing the right side of the Text box being clipped. I've tried setting the margin to various values but the right side of the text box is clipped, it looks kind of ugly. Any ideas there?
Thanks,
HedleyWednesday, April 15, 2009 3:39 PM -
Since the ListViewItem represents an entire row of data in a GridView, not just a column of data, wouldn't this make the text box the size of the row, and not the column?Wednesday, April 15, 2009 5:59 PM
-
That's a good point, and would explain why the right side of my text box appears to be clipped.
HedleyWednesday, April 15, 2009 6:13 PM