Freezable

참조 사이트 : WPF : 8. DataGridColumn의 Visibility 바인딩하는 방법 - LC’s 개발 블로그

우선 코드를 먼저 적자면

        <DataGrid CanUserAddRows="False" CanUserDeleteRows="False">
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="Column1" Header="Column1" />
                <DataGridTextColumn Header="Column2" Visibility="{Binding Column2Visible, Converter={StaticResource BoolToVisibilityConverter}}" />
            </DataGrid.Columns>
        </DataGrid>
        <CheckBox Content="Column Visible" IsChecked="{Binding Column2Visible, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock Text="Test" Visibility="{Binding Column2Visible, Converter={StaticResource BoolToVisibilityConverter}}" />

테스트를 해보면 TextBlock는 정상적으로 Visible이 변경 되는데 Column은 변경 되지 않습니다.

System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. 

가 발생 합니다.

확인해 보기 위해 다음과 같은 코드를 추가 해 보면

// xaml
        <Button
            Command="{Binding TestCommand}"
            CommandParameter="{Binding ElementName=Column1}"
            Content="Test" />
// cs
	private void Test(DataGridTextColumn column)
	{
		try
		{
			VisualTreeHelper.GetParent(column);
		}
		catch (Exception ex)
		{
			MessageBox.Show(ex.Message);
		}
	}

image
와 같은 exception을 확인 할 수 있습니다.

위 문제를 해결 하기 위해선 Freezable을 가져다 쓰면 됩니다.

// xaml
        <DataGrid CanUserAddRows="False" CanUserDeleteRows="False">
            <DataGrid.Resources>
                <local:VisibleBindingProxy x:Key="Culmn2VisiblePlory" Visible="{Binding Column2Visible, Converter={StaticResource BoolToVisibilityConverter}}" />
            </DataGrid.Resources>
            <DataGrid.Columns>
                <DataGridTextColumn x:Name="Column1" Header="Column1" />
                <DataGridTextColumn Header="Column2" Visibility="{Binding Visible, Source={StaticResource Culmn2VisiblePlory}}" />
            </DataGrid.Columns>
        </DataGrid>
        <CheckBox Content="Column Visible" IsChecked="{Binding Column2Visible, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
        <TextBlock Text="Test" Visibility="{Binding Column2Visible, Converter={StaticResource BoolToVisibilityConverter}}" />

// cs
public class VisibleBindingProxy : Freezable
{
	public Visibility Visible
	{
		get { return (Visibility)GetValue(VisibleProperty); }
		set { SetValue(VisibleProperty, value); }
	}
	public static readonly DependencyProperty VisibleProperty =
		DependencyProperty.Register("Visible", typeof(Visibility), typeof(VisibleBindingProxy), new PropertyMetadata(Visibility.Visible));
	protected override Freezable CreateInstanceCore()
	{
		return new VisibleBindingProxy();
	}
}
3개의 좋아요

아직 Freezable을 알고 써본적이 없는데, 혹시 대략적으로 이해하신 바를 알려주실 수 있으실까요?

MSDN을 보면 무슨말인지…잘 모르겠습니다 ㅠㅠ

1개의 좋아요

DataGridColumn 자체는 VisualTree에 참여하고 있지 않을겁니다. 그래서 DataContext 에서 바인딩 패스 찾기는 실패하니, 간접적으로 리소스를 통해 리소스를 소스로 해서 경로를 찾아오면 됩니다. 그를 위해서 Freezable 을 상속 받아 구현하고 리소스를 선언해 사용합니다.

Freezable의 부모인 DependenyObject 를 상속 받아도 되는데요. Freezable을 받으면 객체를 변경 불가능한 상태로 선언함으로써 쪼금 더 활용할 여지가 생깁니다.

3개의 좋아요

Freezable은 내부적으로 이벤트 및 스토리보드(애니메이션) 변경 추적을 제공 합니다.

Freezable.Changed 이벤트 (System.Windows) | 마이크로소프트 런(Microsoft T


Freezable은 해당 객체가 CanFreeze 속성으로 고정 되어 있다면

해당 객체가 변경 되었을때 바인딩시 통보를 하지 않지만,

고정 되어 있지 않다면 바인딩시 부모 관찰자에게 통보를 받을 수 있습니다.

때문에 Freezable을 상속 받음 으로써 DataGridColumn 까지 변경 통보 처리가 되어 정상적으로 바인딩이 처리 될 수 있다고 보시면 됩니다.

2개의 좋아요

아하 요약하자면 바인딩 된 객체에 대해 원래라면 Notify를 줄 수 없는 컨트롤에 대해서, Notify를 줄 수 있도록 도와주는 기능을 하는 것이군요.

ChatGPT를 통해 BindingProxy라는 이름으로 만들어 주는 것을 사용한 적이 있었는데 그래서 가능했던 것이군요.

감사합니다!

1개의 좋아요