【问题标题】:Set a Columndefinition width from code behind从后面的代码中设置 Columndefinition 宽度
【发布时间】:2012-09-20 06:01:20
【问题描述】:

我需要根据一些在后面的代码中完成的计算,在数据模板中为列表视图设置列定义的宽度。所以我得到了这个:

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

此数据模板作为 ItemTemplate 绑定到 ListView。如何访问“gridColumnGraph”?在显示列表视图之前,我需要此访问权限 - 而不是在选择项目时。

非常感谢!

【问题讨论】:

    标签: wpf listview datatemplate


    【解决方案1】:

    使用数据绑定将 Columndefinition.Width-Property 绑定到代码隐藏或 ViewModel 中的属性之一。

    确保您的 ViewModel 继承自 INotifiyPropertyChanged。 创建一个调用 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);
        }
    }
    

    创建属性:

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

    绑定到属性:

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

    将 DataContext 设置为 ViewModel:

    this.DataContext = new ViewModel();
    

    在代码隐藏中更改 CDWidth:

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

    【讨论】:

    • 好吧 - 我不想在这里使用数据绑定。我必须遍历所有 listview-Items 并通过代码计算网格列宽。然后我想为该列设置此值。我不知道如何通过数据绑定来做到这一点。
    • 我刚想出了这个解决方案: 。这比您通过数据上下文的解决方案更糟吗?
    猜你喜欢
    • 2015-12-18
    • 1970-01-01
    • 2013-03-22
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    相关资源
    最近更新 更多