C#C
C#3y ago
Denis

❔ User Control with custom dependency properties

I'm developing a user control that is supposed to have two properties bound by a parent control that will be using it.
Initially, I developed the UC like I'm used to - View + ViewModel.

However, I've quickly discovered that I need custom dependency properties that must be written into the View. So, in short, I need help to correctly propagate the bound values back to the ViewModel.

In my Parent ViewModel, I have a

  public ObservableCollection<TemplateAttribute> Templates { get; } = new()
  {
    new TemplateAttribute("Height", AttributeType.Qualitative)
  };


In my parent view, I'm using my custom user control:

<StackPanel Grid.Row="1">
  <Label Content="Attribute options" />
  <views:AttributeFilterBuilderControl TemplateAttributes="{Binding Templates}" />
</StackPanel>


UC View-behind:
public partial class AttributeFilterBuilderControl
{
  public static readonly DependencyProperty TemplateAttributesProperty =
    DependencyProperty.Register(nameof(TemplateAttributes),
      typeof(IEnumerable<TemplateAttribute>),
      typeof(AttributeFilterBuilderControl), new PropertyMetadata(Enumerable.Empty<TemplateAttribute>()));

  public IEnumerable<TemplateAttribute>? TemplateAttributes
  {
    get => (IEnumerable<TemplateAttribute>?)GetValue(TemplateAttributesProperty);
    set => SetValue(TemplateAttributesProperty, value);
  }

  public AttributeFilterBuilderControl() => InitializeComponent();
}


UC VM property:
[ObservableProperty] private IEnumerable<TemplateAttribute>? m_templates;

UC View:
  <UserControl.Style>
    <Style>
      <Setter Property="local:AttributeFilterBuilderControl.TemplateAttributes" Value="{Binding Templates, Mode=OneWayToSource}" />
    </Style>
  </UserControl.Style>


From my debugging, it seems that the Parent
Templates
property getter is never called, and naturally, the setter of the dependency property is also never called.
Any tips?
Was this page helpful?