In my WPF application, I have a DataGrid which is bound to a collection in the viewmodel, but I want the width of the first column to be equal to a property on the viewmodel itself, like so:
public ObservableCollection<Booking> Bookings
{
return repository.Bookings();
}
public int MaxWidth
{
return 100;
}
(I realise there's no point in binding to a fixed property like this - it's for demo purposes)
<UserControl>
<DataGrid DataContext="{Binding Bookings}">
<DataGrid.Columns>
<DataGridTextColumn Width="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}, Path=DataContext.MaxWidth}" Header="Provider" Binding="{Binding Name}" />
</DataGrid.Columns>
</DataGrid>
</UserControl>
But if I do this, the width of the column remains at the default value - i.e. just wide enough to accommodate its value.
What am I doing wrong?
EDIT: Attempted this, to see what happened:
<Label Name="tricky" Content="500" Visibility="Collapsed"></Label>
...
<DataGridTextColumn Width="{Binding ElementName=tricky, Path=Content}" Header="Provider" Binding="{Binding Name}" />
Which did nothing. Is it not possible to set the width dynamically?