Share via

WPF dependency binding could not find source

cat endless 21 Reputation points
2021-09-27T15:16:45.477+00:00

I bound the ischecked property of the checkbox before loading the component

public FileControl()
        {
            RelativeSource relativeSource = new RelativeSource();
            relativeSource.Mode = RelativeSourceMode.FindAncestor;
            relativeSource.AncestorType = typeof(FileControl);
            Binding bind = new Binding() { RelativeSource=relativeSource };
            checkBox.SetBinding(FileIsCheckedIsCheckedProperty,bind);
            InitializeComponent();

        }

Custom dependencies:

public Nullable<bool> FileIsChecked
        {
            get { return (Nullable<bool>)GetValue(FileIsCheckedIsCheckedProperty); }
            set { SetValue(FileIsCheckedIsCheckedProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ChcckBoxIsChecked.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty FileIsCheckedIsCheckedProperty =
            DependencyProperty.Register("FileIsChecked", typeof(Nullable<bool>), typeof(FileControl), new FrameworkPropertyMetadata(false));

Then run in MainWindow with an error:

CheckBox.FileIsChecked Nullable`1 Source not found: RelativeSource FindAncestor, AncestorType='FileOperator.FileControl', AncestorLevel='1'。

I have no problem binding XAML in the foreground and can access it normally:

<CheckBox Name="checkBox" IsChecked="{Binding IsChecked, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:FileControl}}}">
                </CheckBox>
Developer technologies | Windows Presentation Foundation
Developer technologies | XAML
Developer technologies | XAML

A language based on Extensible Markup Language (XML) that enables developers to specify a hierarchy of objects with a set of properties and logic.

Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.

0 comments No comments

1 answer

Sort by: Most helpful
  1. Viorel 127K Reputation points
    2021-09-27T15:38:42.6+00:00

    Try moving the InitializeComponent( ) line to the beginning.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.