wpf Listbox item 컨트롤에 IsSelected 활용

Eden·2023년 5월 15일

ListBox에 DataTemplate으로 Item을 설정할때 선택된 항목에 대해서만 삭제 버튼이 도시되도록 하고싶었다.
이를 위해서는 ListBoxItem의 IsSelected 속성을 삭제 버튼 visibility에 바인딩 시켜야했는데 열심히 구글링하여 방법을 찾았다

 <UserControl.Resources> //UserControl or Window
 	<BooleanToVisibilityConverter x:Key="visibilityConverter"/> //Bool 변수값을 visibility 값으로 변경
 </UserControl.Resources>
...
<ListBox ...
	<ListBox.ItemTemplate>
    	<DataTemplate>
        	<Grid ...
            	<Grid ...
                	<Button Content="X" Command="{Binding }" 
                    Visibility="{Binding Path=IsSelected ,Mode=TwoWay, 
                    RelativeSource={RelativeSource FindAncestor,   //부모컨트롤 속성값을 사용                  AncestorType={x:Type ListBoxItem}},
                    Converter={StaticResource visibilityConverter}}"> //IsSelected는 bool 변수이기때문에 visibility로 변경해주어야함
                    
...

추가적으로 구글링을 통해 알게된점
RelativeSource 출처 : https://jandari91.github.io/posts/wpf-RelativeSource/
정리

<TextBlock Text="{Binding RelativeSource={RelativeSource self}, Path=FontFamily}" /> 
// 자기자신의 속성을 사용 -> TextBlock에 적용된 FontFamily값이 Text로 도시됨

 <StackPanel Orientation="Horizontal">
    <TextBlock Text="{Binding Path=Orientation, 
    RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}}"/>
</StackPanel>
//자신의 부모 객체의 속성값을 사용 



<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Path=Orientation, 
        RelativeSource={RelativeSource AncestorType={x:Type StackPanel},
        AncenstorLevel=2}}"/>
    </StackPanel>
</StackPanel>
// 타입이 같은 상위 객체가 중복될때 AncenstorLevel을 사용해 원하는 객체 선택



<ControlTemplate TargetType="{x:Type Button}"> 
    <Border x:Name="_pBorder" BorderThickness="2" BorderBrush="Black" CornerRadius="20"> 
        <Border.Background> 
            <LinearGradientBrush StartPoint="0 0.5" EndPoint="1 0.5">
                <GradientStop Offset="0.0" Color="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Background.Color}" />
                <GradientStop Offset="0.9" Color="White" />
            </LinearGradientBrush>
        </Border.Background>
        <ContentPresenter Margin="2" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />
    </Border>
</ControlTemplate>
//ControlTemplate 정의 엘리먼트 일 경우



<StackPanel x:Name="Panel1" Orientation="Vertical">
    <StackPanel x:Name="Panel2" Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Orientation, ElementName=Panel1}"/>
        </StackPanel>
</StackPanel>
<TextBlock Text="{Binding Path=Orientation, ElementName=Panel2}"/>
x:Name으로 Control 찾기
profile
주섬주섬..

0개의 댓글