-
[WPF] Binding RelativeSource, ElementNameC#/WPF 2023. 3. 3. 08:58
CommandParameter Binding 시 ElementName 사용 예시
Command Binding 시 RelativeSource 사용 예시
<dxmvvm:Interaction.Behaviors> <dxmvvm:EventToCommand EventName="ItemClick" Command="{Binding DataContext.ItemClickCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" PassEventArgsToCommand="True"/> </dxmvvm:Interaction.Behaviors>
한 단계 위의 UserControl소스의 DataContext의 ItemClickCommand에 바인딩.
■ Binding 태그 확장의 RelativeSource 속성을 사용하는 방법을 보여준다.
▶ TextBlock 자신이 바인딩 소스인 경우 (C#)
<TextBlock Text="{Binding RelativeSource={RelativeSource self}, Path=FontFamily}" />
여기서 self는 <TextBlock>
TextBlock의 DataContext를 접근하려는 경우는
<TextBlock Text="{Binding RelativeSource={RelativeSource self}, Path=DataContext.PropertyName}" />
이런 식으로 DataContext.프로퍼티네임 으로 접근
▶ TextBlock 기준 1단계 위의 StackPanel이 바인딩 소스인 경우 (C#)
<StackPanel TextBlock.FontSize="12" > <StackPanel HorizontalAlignment="Center" Orientation="Horizontal"> <TextBlock Text="This TextBlock is inside a StackPanel with " /> <TextBlock Text= "{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}, Path=Orientation}" /> <TextBlock Text=" orientation" /> </StackPanel> </StackPanel>
▶ TextBlock 기준 2단계 위의 StackPanel이 바인딩 소스인 경우 (C#)
<StackPanel TextBlock.FontSize="12" > <StackPanel HorizontalAlignment="Center" Orientation="Horizontal"> <TextBlock Text="The parent StackPanel has " /> <TextBlock Text= "{Binding RelativeSource={RelativeSource AncestorType={x:Type StackPanel}, AncestorLevel=2}, Path=Orientation}" /> <TextBlock Text=" orientation" /> </StackPanel> </StackPanel>
▶ ControlTemplate 정의 엘리먼트가 바인딩 소스인 경우 (C#)
<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>
https://icodebroker.tistory.com/692
728x90'C# > WPF' 카테고리의 다른 글
[WPF] Snoop (0) 2023.03.03 [WPF] Multiple Binding (0) 2023.03.03 [WPF] TabItem Header(Caption) (0) 2023.03.02 [WPF] JsonConvert, 직렬화 (0) 2023.02.22 [WPF] .net restore 명령어 (0) 2023.02.17 댓글