Note that there are some explanatory texts on larger screens.

plurals
  1. POCreating a CustomUserControl with a DependencyProperty of type ObservableCollection
    primarykey
    data
    text
    <p>I am trying to create a CustomUserControl in WPF. This CustomUserControl contains a DependencyProperty of type ObservableCollection.</p> <p>My goal is to be able to:</p> <ul> <li>Be able to set the collection directly in the xaml code</li> <li>Be able to bind the collection to a collection in my ViewModel</li> <li>Be able to set the collection using a style setter</li> <li>Have a different instance of the collection per instance of my CustomUserControl.</li> </ul> <p>Here is what I have right now:</p> <pre><code>&lt;my:CustomUserControl ImageList={Binding imgList}/&gt; </code></pre> <p>ImageList is defined as the following:</p> <pre><code>public static readonly DependancyProperty ImageListProperty = DependancyProperty.Register ("ImageList", typeof(List&lt;ImageSource&gt;), typeof(Switch)); public List&lt;ImageSource&gt; ImageList { get { return (List&lt;ImageSource&gt;)GetValue(ImageListProperty); } set { SetValue(ImageListProperty, value); } } </code></pre> <p>In order to have a new instance of ImageList per CustomUserControl, I have added the following line in the ctor of CustomUserControl:</p> <pre><code>public CustomUserControl(){ ... SetValue(ImageListProperty, new List&lt;ImageSource&gt;()); } </code></pre> <p>Now, the following code examples work:</p> <pre><code>&lt;my:CustomUserControl&gt; &lt;my:CustomUserControl.ImageList&gt; &lt;BitmapImage UriSource="Bla.png"/&gt; &lt;BitmapImage UriSource="Bla2.png"/&gt; &lt;/my:CustomUserControl.ImageList&gt; &lt;/my:switch&gt; </code></pre> <p>And this works too:</p> <pre><code>&lt;my:CustomUserControl ImageList={Binding imgList}/&gt; </code></pre> <p>But this <strong>does not</strong>:</p> <pre><code>&lt;Style TargetType="my:CustomUserControl"&gt; &lt;Setter Property="my:CustomUserControl.ImageList"&gt; &lt;BitmapImage UriSource="Bla.png"/&gt; &lt;BitmapImage UriSource="Bla2.png"/&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>This leaves all instances with an empty ImageList.</p> <p>P.S. This is pseudo-code as I don't recall the exact syntax.</p> <p>Thanks!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload