【问题标题】:Is there any way to temporarily detach a binding in WPF?有什么方法可以暂时分离 WPF 中的绑定?
【发布时间】:2010-11-24 05:25:00
【问题描述】:

背景:

我有一个 ListView/GridView 有几列。在某些情况下,仅显示部分列。由于 WPF 中没有 GridViewColumns 的 Visible 属性,因此我将要隐藏的列的宽度设置为零。从视觉上看,这达到了预期的效果(我实际上将ControlTemplate 修改为GridViewColumnHeader,这样用户就不可能意外展开任何隐藏的列)。

问题:

问题是隐藏列的绑定仍在起作用,它们正在尝试查找不存在的数据。在这种情况下,它会导致 IndexOutOfRangeException,因为它试图查找绑定到的 DataTable 上不存在的列名。

问题:

如何暂时禁用或分离隐藏列的绑定?或者,如果您有更好的解决方案,请提出建议。

谢谢!

【问题讨论】:

    标签: wpf data-binding xaml binding


    【解决方案1】:

    啊,我想我明白了。 IValueConverter 救援。

    这是我想出的解决方案,以防其他人遇到同样的问题:

    第 1 步。创建转换器。

    IValueConverter 检查索引是否超出范围,如果超出范围,则返回空字符串。请注意,我使用转换器的parameter 来保存列名。

    public class DataRowViewToCellString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            DataRowView row = (DataRowView)value;
            string columnName = (string)parameter;
            if (row.DataView.Table.Columns.Contains(columnName))
                return row[columnName].ToString();
            else
                return Binding.DoNothing;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
    

    第 2 步。将转换器放入DataTemplate。

    <local_converters:DataRowViewToCellString
        x:Key="TaskWindow_DataRowViewToCellString" />
    
    <DataTemplate
        x:Key="TaskWindow_Column4Template">
        <TextBlock
            Text="{Binding Converter={StaticResource TaskWindow_DataRowViewToCellString}, ConverterParameter=Column4}" />
    </DataTemplate>
    

    第 3 步。引用“有时隐藏”GridViewColumn 中的模板。

    <ListView ... >
        <ListView.View>
            <GridView ... >
                ...
                <GridViewColumn
                    Header="SometimesHiddenColumn"
                    CellTemplate="{StaticResource TaskWindow_Column4Template}">
            </GridView>
        </ListView.View>
    </ListView>
    

    编辑

    根据 Dennis Roche 的建议,在列名超出范围的情况下,将转换器的返回值从 string.Empty 更改为 Binding.DoNothing。

    【讨论】:

    • 我同意这是解决您问题的好方法。我会提出的唯一建议是将返回 String.Empty 更改为返回 Binding.DoNothing。
    猜你喜欢
    • 2011-01-09
    • 1970-01-01
    • 2020-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-21
    • 1970-01-01
    相关资源
    最近更新 更多