[WPF] DataGridColumn Binding 其它來源的屬性

  • 1237
  • 0

摘要:[WPF] DataGridColumn Binding 其它來源的屬性

由於不管是 DataGridCheckBoxColumn 還是 DataGridTextColumn 等,

都沒有像其他大部分控制項會繼承 System.Windows.Media.Visual,

故想 Binding 除了 DataGrid 的 ItemsSource 以外的 DataContext,

需要其他的方式,目前找到兩篇解決方式:

http://stackoverflow.com/questions/7711275/bind-datagrid-column-visibility-mvvm

http://stackoverflow.com/questions/22073740/binding-visibility-for-datagridcolumn-in-wpf

 

挑了最簡單的方法測試成功:


        <FrameworkElement x:Name="dummyElement" Visibility="Collapsed"/>
        <StackPanel>
            <DataGrid>
                <DataGrid.Columns>
                    <DataGridCheckBoxColumn Header="CheckBox" Visibility="{Binding DataContext.IsColumnVisibile, Source={x:Reference dummyElement}}"></DataGridCheckBoxColumn>
                    <DataGridTextColumn Header="TextBox"></DataGridTextColumn>
                </DataGrid.Columns>
            </DataGrid>
            <Button Content="VisibleOrCollapsed" Command="{Binding MyCommand}"></Button>
        </StackPanel>

        /// 
        ///  
        /// 
        private Visibility _isColumnVisibile = Visibility.Collapsed;

        /// 
        ///  
        /// 
        public Visibility IsColumnVisibile
        {
            get
            {
                return _isColumnVisibile;
            }
            set
            {
                Set(() => IsColumnVisibile, ref _isColumnVisibile, value);
            }
        }

        private RelayCommand _myCommand;

        /// 
        /// Gets the MyCommand.
        /// 
        public RelayCommand MyCommand
        {
            get
            {
                return _myCommand
                    ?? (_myCommand = new RelayCommand(
                    () =>
                    {
                        IsColumnVisibile = (IsColumnVisibile == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible;
                    }));
            }
        }