工作 · 2023年6月13日 0

WPF中DataGrid列根据条件隐藏

一、采用代理

  1. xaml的Resources中添加一个FrameworkElement的代理
    <Window.Resources>
    <FrameworkElement x:Key=”Proxy” DataContext=”{Binding}”/>
    </Window.Resources>
  2. 用一个隐藏的ContentControl绑定FrameworkElement代理
    <ContentControl Visibility=”Collapsed” Content=”{StaticResource Proxy}”/>
  3. 用代理做Visibility的数据源
    <DataGridTextColumn Header=”列二” Visibility=”{Binding DataContext.IsVisibility,Source={StaticResource Proxy}}”/>

二、使用Freezable

  1. BindingProxy类
public class BindingProxy:Freezable
{
protected override Freezable CreateInstanceCore()
{
return new BindingProxy();
//throw new NotImplementedException();
}

public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));

public object Data
{
get { return (object)GetValue(DataProperty); }
set { SetValue(DataProperty, value); }
}
}

2.XAML引用BindingProxy

<local:BindingProxy x:Key="proxy" Data="{Binding}"/>

3.Visibility绑定

<DataGridTextColumn Header="列三" Visibility="{Binding Data.IsVisibility,Source={StaticResource proxy}}"/>