为什么在DataGrid中使用Browsable(false)不能隐藏列?

3
在我的WPF应用程序中,我想通过将[Browsable(false)]添加到某些属性来隐藏DataGrid中绑定的ItemsSource列。但是,无论是否有Browsable(false),所有列都可见。
我的模型:
public class Room : INotifyPropertyChanged
{
    private int id;
  ...
    [Browsable(false)]
    public int Id
    {
        get
        {
            return this.id;
        }
        set
        {
            this.id = value;
            this.OnPropertyChanged("Id");
        }
    }
    ...
    public Room()
    {
    }
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged;
        if (propertyChangedEventHandler != null)
        {
            propertyChangedEventHandler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    public event PropertyChangedEventHandler PropertyChanged;
}

查看:

<DataGrid Grid.Row="1" ItemsSource="{Binding Rooms}" SelectedItem="{Binding SelectedRoom, Mode=TwoWay}" />

如何使用Browsable(false)来隐藏列?
3个回答

2

你可以在DataGrid上挂接AutoGeneratingColumn事件来隐藏它们(参见https://dev59.com/A3E85IYBdhLWcg3wXCMv#3794324)。

public class DataGridHideBrowsableFalseBehavior : Behavior<DataGrid>
{
    protected override void OnAttached()
    {
        AssociatedObject.AutoGeneratingColumn += AssociatedObject_AutoGeneratingColumn;
        base.OnAttached();
    }

    private void AssociatedObject_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
    {
        if (((PropertyDescriptor)e.PropertyDescriptor).IsBrowsable == false)
            e.Cancel = true;
    }
}


<DataGrid
    ItemsSource="{Binding Path=DataGridSource, Mode=OneWay}"
    AutoGenerateColumns="true">
        <i:Interaction.Behaviors>
            <behaviors:DataGridHideBrowsableFalseBehavior>
             </behaviors:DataGridHideBrowsableFalseBehavior>
        </i:Interaction.Behaviors>
</DataGrid>

0
很抱歉,您不能这样做。 Browsable 属性仅影响可视化设计器的属性视图,在运行时没有任何影响...

如需更多信息,请查看 MSDN 关于BrowsableAttribute的页面


-1

在你的代码中不要调用 this.OnPropertyChanged("Id");


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接