zpete
zpete

Reputation: 1765

Set a Columndefinition width from code behind

I need to set the width of a columndefinition within a datatemplate for a listview based on some computation which is done in code behind. So I got this:

<DataTemplate x:Key="dataTemplateForListview">
        <Border>
        <Grid>                
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="80" x:Name="gridColumnGraph" />
                <ColumnDefinition Width="*" />
            </Grid.ColumnDefinitions>
         ...
        </Grid>
       </Border>
</DataTemplate>

This Datatemplate is Bound to a ListView as the ItemTemplate. How do I get Access to "gridColumnGraph"? I need this access before the listview gets displayed - not when an Item is selected.

Thanks a lot!

Upvotes: 1

Views: 1411

Answers (1)

Florian Gl
Florian Gl

Reputation: 6014

Use Databinding to bind the Columndefinition.Width-Property to one of your Properties in code-behind or your ViewModel.

Make sure your ViewModel inherits from INotifiyPropertyChanged. Create a method which calls the PropertyChanged-Event:

public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        var e = new PropertyChangedEventArgs(propertyName);
        handler(this, e);
    }
}

Create the property:

private double _cdWidth;
public double CDWidth
{
    get { return _cdWidth; }
    set { _cdWidth= value; OnPropertyChanged("CDWidth"); }
}

Bind to the property:

<ColumnDefinition Width={Binding Path=CDWidth}/>

Set DataContext to ViewModel:

this.DataContext = new ViewModel();

Change CDWidth in codebehind:

ViewModel vm = (ViewModel)this.DataContext;
vm.CDWidth = 10;

Upvotes: 2

Related Questions