Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
[WPF/DataGrid] : Binding `DataGridTextColumn.Visibility` to `CheckBox.IsChecked` with a hidden proxy object
<Window x:Class="BindDataGridColumnVisibility.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:BindDataGridColumnVisibility"
mc:Ignorable="d"
Title="MainWindow" Height="376" Width="634" WindowState="Maximized">
<Grid>
<Grid.Resources>
<!-- BooleanをVisibilityに変換するコンバータ -->
<BooleanToVisibilityConverter
x:Key="BooleanToVisibilityConverter" />
<!-- チェックボックスにバインドしたプロキシー -->
<FrameworkElement x:Key="ProxyColumnVisibility"
DataContext="{Binding Path=IsChecked, ElementName=checkBoxShowColumn}"/>
</Grid.Resources>
<!-- プロキシー経由でチェックボックスにバインドした
非表示コントロール -->
<ContentControl Visibility="Collapsed"
Content="{StaticResource ProxyColumnVisibility}"/>
<CheckBox x:Name="checkBoxShowColumn" Content="列を表示"
HorizontalAlignment="Left" Margin="10,10,0,0"
VerticalAlignment="Top" />
<DataGrid x:Name="dataGrid" Margin="10,30,10,10"
AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="常に表示されてる列" />
<!-- ↓のVisibilityでBinding -->
<DataGridTextColumn
Header="チェックボックスで表示状態を切り替えられる列"
Visibility="{Binding DataContext, Source={StaticResource ProxyColumnVisibility},Converter={StaticResource BooleanToVisibilityConverter}}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment