通过绑定修改DataGrid的Column的Visibility

2017-05-14 11:44:08来源:CSDN作者:xiudou_123人点击

问题:因为DataGridColumns不是可视树的一部分,他们不能使用datagriddatacontext

解决方法1:代理类

    public class BindingProxy : Freezable    {        #region Overrides of Freezable        protected override Freezable CreateInstanceCore()        {            return new BindingProxy();        }        #endregion        public object Data        {            get { return (object)GetValue(DataProperty); }            set { SetValue(DataProperty, value); }        }        public static readonly DependencyProperty DataProperty =            DependencyProperty.Register("Data", typeof(object),                                         typeof(BindingProxy));}


<DataGrid …>        <DataGrid.Resources>            <local:BindingProxy x:Key="proxy" Data="{Binding}"></local:BindingProxy>        </DataGrid.Resources>        <DataGrid.Columns>        <DataGridTextColumn Header="Grade"            Visibility="{Binding Data.MyColumnVisibility, Source={StaticResource proxy}}"            Binding="{Binding Path=Grade}">        </DataGridTextColumn>    </DataGrid.Columns></DataGrid>

 解决方法2:代元素

1.在用户控件的Resources里加一个代理FrameworkElement,并绑定控件的datacontex

2.把这个代理控件放在一个不可见的ContentControl

<FrameworkElement x:Name="dummyElement" Visibility="Collapsed" DataContext="{Binding}"/>


3.将DataGridColumnVisibility绑定Datacontext中的属性,比如IsEnable、或NoVisibilitySource采用x:Reference dummyElement

4.如果绑定属性是bool类型,还要使用Converter转换一下

<DataGrid …>    <DataGrid.Columns>        <DataGridTextColumn Header="No."             Visibility="{Binding DataContext.IsEnable, Source={x:Reference dummyElement},Converter={StaticResource BooleanToVisibilityConverter}}"            Binding="{Binding Path=No}">        </DataGridTextColumn>        <DataGridTextColumn Header="Name"            Visibility="{Binding DataContext.NoVisibility, Source={x:Reference dummyElement}}"            Binding="{Binding Path=Name}">        </DataGridTextColumn>    </DataGrid.Columns></DataGrid>


参考网址:http://stackoverflow.com/questions/22073740/binding-visibility-for-datagridcolumn-in-wpf?noredirect=1


代码:http://download.csdn.net/download/xiudou_123/9836031


最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台