Свойство коллекции привязок wpf в UserControl - PullRequest
6 голосов
/ 06 сентября 2011

У меня есть пользовательский UserControl, который содержит коллекцию пользовательских объектов.

public class Question : FrameworkElement
{
    public readonly static DependencyProperty FullNameProperty =
        DependencyProperty.Register("FullName", typeof(string), typeof(Question));

    public readonly static DependencyProperty ShortNameProperty =
        DependencyProperty.Register("ShortName", typeof(string), typeof(Question));

    public readonly static DependencyProperty RecOrderProperty =
        DependencyProperty.Register("RecOrder", typeof(int), typeof(Question));

    public readonly static DependencyProperty AnswerProperty =
        DependencyProperty.Register("Answer", typeof(string), typeof(Question));

    public string FullName
    {
        get { return (string)GetValue(FullNameProperty); }
        set { SetValue(NameProperty, value); }
    }

    public string ShortName
    {
        get { return (string)GetValue(ShortNameProperty); }
        set { SetValue(ShortNameProperty, value); }
    }

    public string Answer
    {
        get { return (string)GetValue(AnswerProperty); }
        set { SetValue(AnswerProperty, value); }
    }

    public int RecOrder
    {
        get { return (int)GetValue(RecOrderProperty); }
        set { SetValue(RecOrderProperty, value); }
    }
}

В моем контрольном коде у меня есть

public readonly static DependencyProperty QuestionsProperty =
        DependencyProperty.Register("Questions", typeof(ObservableCollection<Question>), typeof(FormQuestionReportViewer), 
        new PropertyMetadata(new ObservableCollection<Question>()));


     public ObservableCollection<Question> Questions
     {
        get { return GetValue(QuestionsProperty) as ObservableCollection<Question>; }
        set { SetValue(QuestionsProperty, value); }
     }

И в разметке xaml я могу определить свой контроль следующим образом

    <custom:CustomControl>
        <custom:CustomControl.Questions>
            <custom:Question FullName="smth text" ShortName="smth text" RecOrder="1" Answer="Yes" />
            <custom:Question FullName="smth text" ShortName="smth text" RecOrder="2" Answer="Yes" />
        </custom:CustomControl.Questions>          
    </custom:CustomControl>

Это хорошо работает, но я хочу сделать привязку моего свойства коллекции в xaml таким, как это

    <custom:CustomControl>
        <custom:CustomControl.Questions Items="{binding Path=Questions}">
            <custom:Question FullName="{binding Name}" ShortName="{binding ShortName}" RecOrder="{binding RecOrder}" Answer={binding Answer}" /> 
        </custom:CustomControl.Questions>          
    </custom:CustomControl>

Как я могу сделать это связывание?

1 Ответ

8 голосов
/ 06 сентября 2011

Вам нужно будет предоставить два отдельных свойства, очень похожих на ItemsControl, у которого есть свойства Items и ItemsSource .Похоже, что вы хотите иметь возможность добавлять элементы, используя привязку и явно, добавляя в свою коллекцию.Это поведение будет отличаться от ItemsControl, который позволяет вам использовать только свойство Items или ItemsSource, но не оба одновременно.

Ничто не мешает вам добавить поддержку обоих способов указания элементов,но это будет больше работы с вашей стороны.

Во-первых, вам понадобится свойство DependencyProperty, такое как IEnumerable QuestionsSource, к которому вы можете привязать:

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); }
 }

секунду, вы бынеобходимо обычное свойство CLR, такое как ObservableCollection<Question> Questions, к которому можно явно добавить элементы:

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

Затем вы можете использовать эти свойства следующим образом:

<custom:CustomControl QuestionsSource="{Binding Path=Questions}">
    <custom:CustomControl.Questions>
        <custom:Question FullName="{binding Name}" ShortName="{binding ShortName}" RecOrder="{binding RecOrder}" Answer={binding Answer}" /> 
    </custom:CustomControl.Questions>          
</custom:CustomControl>

Дополнительная работанаступает, когда вы хотите получить полный список предметов.Вам нужно объединить две коллекции в одну коллекцию.Эта объединенная коллекция будет представлена ​​как третье свойство, которое возвращает коллекцию только для чтения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...