wpf binding collection property in UserControl

后端 未结 1 597
春和景丽
春和景丽 2021-02-06 07:24

I have a custom UserControl, which contains collection of custom objects.

public class Question : FrameworkElement
{
    public readonly static DependencyPropert         


        
1条回答
  •  遥遥无期
    2021-02-06 08:16

    You would have to expose two separate properties, much like an ItemsControl which has an Items and ItemsSource property. It looks like you want to be able to add items using a binding and explicitly by adding to your collection. This behavior would differ from an ItemsControl, which only allows you to use the Items or ItemsSource property, but not both at the same time.

    There is nothing preventing you from adding support for both ways of specifying items though, but it would be more work on your part.

    First, you'd need a DependencyProperty, such as IEnumerable QuestionsSource, which you could bind to:

    public readonly static DependencyProperty QuestionsSourceProperty =
        DependencyProperty.Register("QuestionsSource",
            typeof(IEnumerable),
            typeof(FormQuestionReportViewer), 
            new PropertyMetadata(null));
    
     public IEnumerable QuestionsSource
     {
        get { return GetValue(QuestionsSourceProperty) as IEnumerable; }
        set { SetValue(QuestionsSourceProperty, value); }
     }
    

    second, you would need a regular CLR property, such as ObservableCollection Questions, which you could add items to explicitly:

    private ObservableCollection questions = new ObservableCollection();
    public ObservableCollection Questions
     {
        get { return questions; }
     }
    

    Then you could use these properties like so:

    
        
             
                  
    
    

    The extra work comes when you want to get the full list of items. You'd need to union the two collections into a single collection. This unified collection would be exposed as a third property, which returns a read-only collection.

    0 讨论(0)
提交回复
热议问题