-1

I'm new to WPF and what I want to do is below. Here is my XAML code:

...
<DataGridTextColumn Binding="{Binding ShippingNumber}" Header="出荷No." ElementStyle="{DynamicResource TextAlignCenter}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding DivisionDisplay}" Header="区分" ElementStyle="{DynamicResource TextAlignCenter}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding ShippingDestinationCode}" Header="出荷先コード" ElementStyle="{DynamicResource TextAlignCenter}" IsReadOnly="True"/>
<DataGridTextColumn Binding="{Binding ShippingDestinationNameDisplay}" Header="出荷先名" ElementStyle="{DynamicResource TextAlignCenter}" IsReadOnly="True"/>
    <DataGridTextColumn.ElementStyle>
         <Style TargetType="TextBlock">
             <Setter Property="TextAlignment" Value="Center"/>
             <Setter Property="Width" Value="{Binding DataContext.CustomWidth, ElementName=Page}"/>
         </Style>
     </DataGridTextColumn.ElementStyle>
</DataGridTextColumn>

All the logic code I have to write in ViewModel (not allow in code-behind), in the VM's constructor I set the property CustomWidth = 500 and in the RelayCommand action of Search button I change the value to 300. It's OK to increase ctrl width to 500 at first run(load event), but then I click Search button to shrink it to 300, there is nothing happened.

Can anyone tell me why it did not take affect and how to make it works? Thanks in advance.

Quan Nguyen
  • 562
  • 1
  • 5
  • 20
  • 1
    Your markup is invalid. ShippingDestinationNameDisplay column has a self closing tag and element style is set twice. Although your problem is different I just noted it. – Nikhil Vartak Oct 19 '15 at 04:31

2 Answers2

0

Please take a look at this article [SOURCE] DataGrid column width doesn't auto-update. In short it can't automatically be done as mentioned before but if you want to code it up here is some info in this stack overflow post on how to do it succesfully/dynamically. I think there are two major parts. update the width to 1* and notify property changed.

private void dg_TargetUpdated(object sender, DataTransferEventArgs e)
{
    dg.Columns[0].Width = 0;
    dg.UpdateLayout();
    dg.Columns[0].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
}

notify property changed.

<DataGridTextColumn Binding="{Binding First}" Width="1*"/>
<DataGridTextColumn Binding="{Binding Last, NotifyOnTargetUpdated=True}" 
Community
  • 1
  • 1
SteckDEV
  • 489
  • 4
  • 13
-1

DataGrid does not reduce it's size once it is increased due to say some larger cell content, and if you have set ColumnWidth="SizeToCells". You have to write your own logic for this to happen, or you can set it to SizeToHeader, and show larger cell content in tooltip of that cell.

AnjumSKhan
  • 9,647
  • 1
  • 26
  • 38