A
A
Andrey Golubkov2017-11-08 02:26:06
WPF
Andrey Golubkov, 2017-11-08 02:26:06

How to forward a property from a WPF control?

I have this property in my control

public ObservableCollection<object> Items
        {
            get => (ObservableCollection<object>)GetValue(ItemsProperty);
            set
            {
                SetValue(ItemsProperty, value);       
            }
        }

There is also a static constructor with DependencyProperty
public static readonly DependencyProperty ItemsProperty;

        
        static FilteredListBox()
        {
            ItemsProperty = DependencyProperty.Register("Items",
                                                       typeof(ObservableCollection<object>),
                                                       typeof(FilteredListBox),
                                                       new FrameworkPropertyMetadata(new ObservableCollection<object>(),
                                                                                     FrameworkPropertyMetadataOptions
                                                                                             .AffectsMeasure
                                                                                     | FrameworkPropertyMetadataOptions
                                                                                             .AffectsRender,
                                                                                     new PropertyChangedCallback(OnItemsChanged)));
        }

And in the markup of the control, there is a boxing sheet that is attached to the property of the control.
<ListBox Name="_listBox"
                 ItemsSource="{Binding Items}" 
        />

When I use my control on the form, the binding does not work, i.e. elements are added to the collection. but they don't appear in the list.
<ctrls:MyListBox Items="{Binding Departments}"/>
How to properly forward a property from a control?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
L
LootKeeper, 2017-11-08
@LootKeeper

Try to specify the binding in the UserControl itself in the ListBox like this:

<ListBox Name="_listBox"
                 ItemsSource="{Binding Items, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" 
        />

In general, if you are doing a project "for yourself", then it's easier to do it all through the Mvvm pattern. Bindings in this case are very convenient to do, and you can do without DependencyProperty, and write all the logic in the ViewModel for the desired UC.

L
lam0x86, 2017-11-08
@lam0x86

Firstly, you need to use TemplateBinding (after all, did you redefine the template for your control?)
Secondly, you cannot write "new ObservableCollection()" in the metadata, because all your controls will refer to the same collection.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question