WPF DataGridTextColumn 无法通过RelativeSource获取DataContext

  1. 添加代理

 public class BindingProxy:Freezable
    {
        protected override Freezable CreateInstanceCore()
        {
            return new BindingProxy();
            
        }

        public object DataContext
        {
            get
            {
                return (object)GetValue(DataContextProperty);
            }
            set
            {
                SetValue(DataContextProperty, value);
            }
        }

        // Using a DependencyProperty as the backing store for DataContext.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DataContextProperty =
            DependencyProperty.Register("DataContext", typeof(object), typeof(BindingProxy), new PropertyMetadata(null));
    }
  1. 引入资源
        <wpfDataContextSample:BindingProxy x:Key="BindingProxy" DataContext="{Binding}"></wpfDataContextSample:BindingProxy>

  1. 绑定
 <DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Students}">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Visibility="{Binding DataContext.IsShow,Source={StaticResource BindingProxy},Converter={StaticResource Converter}}"></DataGridTextColumn>
            </DataGrid.Columns>
        </DataGrid>

[参考]
1

posted @ 2025-03-12 10:56  Hey,Coder!  阅读(10)  评论(0)    收藏  举报