WPF Binding in custom control with nested dependency properties.
Hi,
I have created a custom control that should work similar to a data grid (with columns containing certain properties).
The main class that contains the columns collection object is of type UserControl. The columns collection object contains a collection of column models, which also contains some other properties and nestem models. All of those objects are of type DependecyObject.
Here are some examples of my structure:
public partial class GridControl : UserControl
{
public ColumnsCollection ColumnsCollection
{
get { return (ColumnsCollection)GetValue(ColumnsCollectionProperty); }
set { SetValue(ColumnsCollectionProperty, value); }
}
public static readonly DependencyProperty ColumnsCollectionProperty =
DependencyProperty.Register(
name: nameof(ColumnsCollection),
propertyType: typeof(ColumnsCollection),
ownerType: typeof(GridControl));
{......}
public class ColumnsCollection : DependencyObject
{
#region Properties
public ObservableCollection<Column> ColumnItems
{
get { return (ObservableCollection<Column>)GetValue(ColumnItemsProperty); }
set { SetValue(ColumnItemsProperty, value); }
}
public static readonly DependencyProperty ColumnItemsProperty =
DependencyProperty.Register(
name: nameof(ColumnItems),
propertyType: typeof(ObservableCollection<Column>),
ownerType: typeof(ColumnsCollection),
typeMetadata: new PropertyMetadata(default));
{...}
public class Column : DependencyObject
{
public string Header
{
get { return (string)GetValue(HeaderProperty); }
set { SetValue(HeaderProperty, value); }
}
public static readonly DependencyProperty HeaderProperty =
DependencyProperty.Register(
name: nameof(Header),
propertyType: typeof(string),
ownerType: typeof(Column),
typeMetadata: new PropertyMetadata(default));
{....}
The definition in xaml looks like this:
<gridControl:GridControl>
<gridControl:GridControl.ColumnsCollection>
<gridControl:ColumnsCollection>
<gridControl:ColumnsCollection.ColumnItems>
<gridControl:Column Header="{Binding DataContext.SomeProperty}" />
</gridControl:ColumnsCollection.ColumnItems>
</gridControl:ColumnsCollection>
</gridControl:GridControl.ColumnsCollection>
</gridControl:GridControl>
I have a problem with binding to a property stored in my DataContext of the view (any other binding to StaticResources works fine), in which my custom control is used. I have tried all approaches - using ElementName that points to my parent UserControl, the RelativeSource with FindAncestor by type approach, nothing has worked for me, the DataContext is null in every case. I receive binding errors like this one:
Cannot find governing FrameworkElement or FrameworkContentElement for target element.
I believe the problem is more about how the dependency objects were defined, maybe I am using the wrong base class or I am missing any additional operation to make it work?
Thanks in advance for any suggestions,
Kind Regards,
Dawid