wpfrelativesource

How to properly bind datacontext RelativeSource in WPF?


I am defining the RelativeSource in my Template in the XAML, with

DataContext="{Binding RelativeSource={RelativeSource Self}}"

I am getting an exception

"A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll

Additional information: Provide value on 'System.Windows.Markup.StaticResourceHolder' threw an exception."

I think the problem is i need to bind this after my Window.Resources declarations but i am not sure how to do this using the <DataContext tags and still use RelativeSource. Thanks!

<Window x:Class="SupportDesk.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Top Echelon Support Desk" Height="554" Width="743" xmlns:my="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input.Toolkit" xmlns:myNewNamespace="clr-namespace:SupportDesk"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Window.Resources>
    <myNewNamespace:BoolToVisibilityConverter x:Key="boolToVis" />

    <Style TargetType="{x:Type TextBlock}"
  x:Key="GridBlockStyle">
        <Setter Property="VerticalAlignment" Value="Center" />
        <Setter Property="Visibility"
 Value="{Binding Path=IsSelected,
     RelativeSource={RelativeSource FindAncestor,
         AncestorType={x:Type ListViewItem}},
     Converter={StaticResource boolToVis},
         ConverterParameter=False}" />
    </Style>
</Window.Resources>

Solution

  • How about setting the DataContext on the immediate child of your window? e.g.

    <Window>
       <Grid DataContext="{Binding RelativeSource={RelativeSource Self}}">
       </Grid>
    </Window>
    

    Would this work for you?