How to properly bind datacontext RelativeSource in WPF?

I define a RelativeSource in my template in XAML,

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

I get an exception

"The first exception event of type" System.Windows.Markup.XamlParseException "occurred in PresentationFramework.dll

Additional information: Provide a value in 'System.Windows.Markup.StaticResourceHolder' throws an exception.

I think the problem is that I need to link this after my Window.Resources declarations, but I'm not sure how to do this using tags <DataContextand still use RelativeSource. Thank!

<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>
+3
source share
1 answer

How to set a DataContext for the immediate child of your window? eg.

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

Will this work for you?

+3

Source: https://habr.com/ru/post/1781658/


All Articles