Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
900
Unable to set column width programatically
posted

I have a grid where some cells contain text that is too long.  When I autosize the columns, the columns can become too wide for the user (over 3000px). I'd like to implement a simple condition where I have a maximum column width, but only when autosizing.  I'd still like the user to be able to size the column.  However, when I tried to set the width after the resize operation, things didn't quite work out.

I wrote a very simple app to illustrate my point:

<Window x:Class="AutoSizeApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ig="http://infragistics.com/DataPresenter"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Vertical">
<Button Click="Button_Click">Auto Resize</Button>
<ig:XamDataPresenter
x:Name="grid"
BindToSampleData="True">
</ig:XamDataPresenter>
</StackPanel>
</Window>

using System.Windows;
using Infragistics.Windows.DataPresenter;

namespace AutoSizeApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)
{
foreach (var field in grid.DefaultFieldLayout.Fields)
{
field.PerformAutoSize();

// Works only the first time around.
double max = 10;
if (field.CellWidthResolved > max)
{
field.Settings.Width = new FieldLength(max);
}
}
}
}
}

When I click the Auto Resize button, the first time around the cells will resize, but the max width will be at 10px, as the code intended.  When the button is clicked a second time, and any subsequent time after that, the 10px setting is completely ignored, and the autosize resizes to the text regardless of how long it is.

How can I cap the width of the columns after a PerformAutoSize() call?