Cannot bind to a collection from ItemsControl template












2















I'm trying to bind a user control property "MyUserControl.Names" to a collection property "Names" of the main window. It doesn't work if I do it in ItemsControl template, but it works if I move the control definition out of the ItemsControl template. Here is the xaml:



<Window x:Class="TestItemsControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestItemsControl"
Height="200" Width="200"
Name="MainControl">
<StackPanel>
<ItemsControl ItemsSource="{Binding Groups, ElementName=MainControl}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- This doesn't work -->
<StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
<TextBlock Text="{Binding .}"/>
<local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- This works -->
<StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
<TextBlock Text="Group3"/>
<local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
</StackPanel>
</StackPanel>
</Window>


MainWindow.xaml.cs contains two dependency properties:



public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
SetValue(GroupsProperty, new ObservableCollection<string>());
SetValue(NamesProperty, new ObservableCollection<string>());

Groups.Add("Group1");
Groups.Add("Group2");
Names.Add("Name1");
Names.Add("Name2");
}

public static readonly DependencyProperty GroupsProperty =
DependencyProperty.Register("Groups", typeof(ObservableCollection<string>), typeof(MainWindow),
new PropertyMetadata(null));

public ObservableCollection<string> Groups
{
get { return (ObservableCollection<string>)GetValue(GroupsProperty); }
set { SetValue(GroupsProperty, value); }
}

public static readonly DependencyProperty NamesProperty =
DependencyProperty.Register("Names", typeof(ObservableCollection<string>), typeof(MainWindow),
new PropertyMetadata(null));

public ObservableCollection<string> Names
{
get { return (ObservableCollection<string>)GetValue(NamesProperty); }
set { SetValue(NamesProperty, value); }
}
}


Here is the result:



enter image description here



The first two rectangles are what ItemsControl generates. The third one is what I have manually added right after the ItemsControl. As you can see, even though the code is exactly the same in both cases, the first two rectangles don't have names, but the third one has. Is there any reason why wouldn't it work with ItemsControl?



Edit:



Here is the code of the MyUserControl.xaml.cs:



public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
SetValue(NamesProperty, new ObservableCollection<string>());
}

public static readonly DependencyProperty NamesProperty = DependencyProperty.Register(
"Names", typeof(ObservableCollection<string>), typeof(MyUserControl),
new PropertyMetadata(null, NamesPropertyChanged));

public ObservableCollection<string> Names
{
get { return (ObservableCollection<string>)GetValue(NamesProperty); }
set { SetValue(NamesProperty, value); }
}

private static void NamesPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var control = (MyUserControl)obj;
var oldCollection = e.OldValue as INotifyCollectionChanged;
var newCollection = e.NewValue as INotifyCollectionChanged;

if (oldCollection != null)
oldCollection.CollectionChanged -= control.NamesCollectionChanged;
if (newCollection != null)
newCollection.CollectionChanged += control.NamesCollectionChanged;

control.UpdateNames();
}

private void NamesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
UpdateNames();
}

private void UpdateNames()
{
NamesPanel.Children.Clear();

if (Names == null)
return;

foreach(var name in Names)
{
var textBlock = new TextBlock();
textBlock.Text = name + ", ";
NamesPanel.Children.Add(textBlock);
}
}
}


MyUserControl.xaml:



<UserControl x:Class="TestItemsControl.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:TestItemsControl"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="300"
Name="ParentControl">
<StackPanel Name="NamesPanel" Orientation="Horizontal"/>
</UserControl>









share|improve this question





























    2















    I'm trying to bind a user control property "MyUserControl.Names" to a collection property "Names" of the main window. It doesn't work if I do it in ItemsControl template, but it works if I move the control definition out of the ItemsControl template. Here is the xaml:



    <Window x:Class="TestItemsControl.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestItemsControl"
    Height="200" Width="200"
    Name="MainControl">
    <StackPanel>
    <ItemsControl ItemsSource="{Binding Groups, ElementName=MainControl}">
    <ItemsControl.ItemTemplate>
    <DataTemplate>
    <!-- This doesn't work -->
    <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
    <TextBlock Text="{Binding .}"/>
    <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
    </StackPanel>
    </DataTemplate>
    </ItemsControl.ItemTemplate>
    </ItemsControl>
    <!-- This works -->
    <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
    <TextBlock Text="Group3"/>
    <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
    </StackPanel>
    </StackPanel>
    </Window>


    MainWindow.xaml.cs contains two dependency properties:



    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    SetValue(GroupsProperty, new ObservableCollection<string>());
    SetValue(NamesProperty, new ObservableCollection<string>());

    Groups.Add("Group1");
    Groups.Add("Group2");
    Names.Add("Name1");
    Names.Add("Name2");
    }

    public static readonly DependencyProperty GroupsProperty =
    DependencyProperty.Register("Groups", typeof(ObservableCollection<string>), typeof(MainWindow),
    new PropertyMetadata(null));

    public ObservableCollection<string> Groups
    {
    get { return (ObservableCollection<string>)GetValue(GroupsProperty); }
    set { SetValue(GroupsProperty, value); }
    }

    public static readonly DependencyProperty NamesProperty =
    DependencyProperty.Register("Names", typeof(ObservableCollection<string>), typeof(MainWindow),
    new PropertyMetadata(null));

    public ObservableCollection<string> Names
    {
    get { return (ObservableCollection<string>)GetValue(NamesProperty); }
    set { SetValue(NamesProperty, value); }
    }
    }


    Here is the result:



    enter image description here



    The first two rectangles are what ItemsControl generates. The third one is what I have manually added right after the ItemsControl. As you can see, even though the code is exactly the same in both cases, the first two rectangles don't have names, but the third one has. Is there any reason why wouldn't it work with ItemsControl?



    Edit:



    Here is the code of the MyUserControl.xaml.cs:



    public partial class MyUserControl : UserControl
    {
    public MyUserControl()
    {
    InitializeComponent();
    SetValue(NamesProperty, new ObservableCollection<string>());
    }

    public static readonly DependencyProperty NamesProperty = DependencyProperty.Register(
    "Names", typeof(ObservableCollection<string>), typeof(MyUserControl),
    new PropertyMetadata(null, NamesPropertyChanged));

    public ObservableCollection<string> Names
    {
    get { return (ObservableCollection<string>)GetValue(NamesProperty); }
    set { SetValue(NamesProperty, value); }
    }

    private static void NamesPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
    var control = (MyUserControl)obj;
    var oldCollection = e.OldValue as INotifyCollectionChanged;
    var newCollection = e.NewValue as INotifyCollectionChanged;

    if (oldCollection != null)
    oldCollection.CollectionChanged -= control.NamesCollectionChanged;
    if (newCollection != null)
    newCollection.CollectionChanged += control.NamesCollectionChanged;

    control.UpdateNames();
    }

    private void NamesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
    UpdateNames();
    }

    private void UpdateNames()
    {
    NamesPanel.Children.Clear();

    if (Names == null)
    return;

    foreach(var name in Names)
    {
    var textBlock = new TextBlock();
    textBlock.Text = name + ", ";
    NamesPanel.Children.Add(textBlock);
    }
    }
    }


    MyUserControl.xaml:



    <UserControl x:Class="TestItemsControl.MyUserControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:local="clr-namespace:TestItemsControl"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="300"
    Name="ParentControl">
    <StackPanel Name="NamesPanel" Orientation="Horizontal"/>
    </UserControl>









    share|improve this question



























      2












      2








      2








      I'm trying to bind a user control property "MyUserControl.Names" to a collection property "Names" of the main window. It doesn't work if I do it in ItemsControl template, but it works if I move the control definition out of the ItemsControl template. Here is the xaml:



      <Window x:Class="TestItemsControl.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="clr-namespace:TestItemsControl"
      Height="200" Width="200"
      Name="MainControl">
      <StackPanel>
      <ItemsControl ItemsSource="{Binding Groups, ElementName=MainControl}">
      <ItemsControl.ItemTemplate>
      <DataTemplate>
      <!-- This doesn't work -->
      <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
      <TextBlock Text="{Binding .}"/>
      <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
      </StackPanel>
      </DataTemplate>
      </ItemsControl.ItemTemplate>
      </ItemsControl>
      <!-- This works -->
      <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
      <TextBlock Text="Group3"/>
      <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
      </StackPanel>
      </StackPanel>
      </Window>


      MainWindow.xaml.cs contains two dependency properties:



      public partial class MainWindow : Window
      {
      public MainWindow()
      {
      InitializeComponent();
      SetValue(GroupsProperty, new ObservableCollection<string>());
      SetValue(NamesProperty, new ObservableCollection<string>());

      Groups.Add("Group1");
      Groups.Add("Group2");
      Names.Add("Name1");
      Names.Add("Name2");
      }

      public static readonly DependencyProperty GroupsProperty =
      DependencyProperty.Register("Groups", typeof(ObservableCollection<string>), typeof(MainWindow),
      new PropertyMetadata(null));

      public ObservableCollection<string> Groups
      {
      get { return (ObservableCollection<string>)GetValue(GroupsProperty); }
      set { SetValue(GroupsProperty, value); }
      }

      public static readonly DependencyProperty NamesProperty =
      DependencyProperty.Register("Names", typeof(ObservableCollection<string>), typeof(MainWindow),
      new PropertyMetadata(null));

      public ObservableCollection<string> Names
      {
      get { return (ObservableCollection<string>)GetValue(NamesProperty); }
      set { SetValue(NamesProperty, value); }
      }
      }


      Here is the result:



      enter image description here



      The first two rectangles are what ItemsControl generates. The third one is what I have manually added right after the ItemsControl. As you can see, even though the code is exactly the same in both cases, the first two rectangles don't have names, but the third one has. Is there any reason why wouldn't it work with ItemsControl?



      Edit:



      Here is the code of the MyUserControl.xaml.cs:



      public partial class MyUserControl : UserControl
      {
      public MyUserControl()
      {
      InitializeComponent();
      SetValue(NamesProperty, new ObservableCollection<string>());
      }

      public static readonly DependencyProperty NamesProperty = DependencyProperty.Register(
      "Names", typeof(ObservableCollection<string>), typeof(MyUserControl),
      new PropertyMetadata(null, NamesPropertyChanged));

      public ObservableCollection<string> Names
      {
      get { return (ObservableCollection<string>)GetValue(NamesProperty); }
      set { SetValue(NamesProperty, value); }
      }

      private static void NamesPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
      {
      var control = (MyUserControl)obj;
      var oldCollection = e.OldValue as INotifyCollectionChanged;
      var newCollection = e.NewValue as INotifyCollectionChanged;

      if (oldCollection != null)
      oldCollection.CollectionChanged -= control.NamesCollectionChanged;
      if (newCollection != null)
      newCollection.CollectionChanged += control.NamesCollectionChanged;

      control.UpdateNames();
      }

      private void NamesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
      {
      UpdateNames();
      }

      private void UpdateNames()
      {
      NamesPanel.Children.Clear();

      if (Names == null)
      return;

      foreach(var name in Names)
      {
      var textBlock = new TextBlock();
      textBlock.Text = name + ", ";
      NamesPanel.Children.Add(textBlock);
      }
      }
      }


      MyUserControl.xaml:



      <UserControl x:Class="TestItemsControl.MyUserControl"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:TestItemsControl"
      mc:Ignorable="d"
      d:DesignHeight="300"
      d:DesignWidth="300"
      Name="ParentControl">
      <StackPanel Name="NamesPanel" Orientation="Horizontal"/>
      </UserControl>









      share|improve this question
















      I'm trying to bind a user control property "MyUserControl.Names" to a collection property "Names" of the main window. It doesn't work if I do it in ItemsControl template, but it works if I move the control definition out of the ItemsControl template. Here is the xaml:



      <Window x:Class="TestItemsControl.MainWindow"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="clr-namespace:TestItemsControl"
      Height="200" Width="200"
      Name="MainControl">
      <StackPanel>
      <ItemsControl ItemsSource="{Binding Groups, ElementName=MainControl}">
      <ItemsControl.ItemTemplate>
      <DataTemplate>
      <!-- This doesn't work -->
      <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
      <TextBlock Text="{Binding .}"/>
      <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
      </StackPanel>
      </DataTemplate>
      </ItemsControl.ItemTemplate>
      </ItemsControl>
      <!-- This works -->
      <StackPanel Background="WhiteSmoke" Height="40" Width="100" Margin="5" HorizontalAlignment="Left">
      <TextBlock Text="Group3"/>
      <local:MyUserControl Names="{Binding Names, ElementName=MainControl}"/>
      </StackPanel>
      </StackPanel>
      </Window>


      MainWindow.xaml.cs contains two dependency properties:



      public partial class MainWindow : Window
      {
      public MainWindow()
      {
      InitializeComponent();
      SetValue(GroupsProperty, new ObservableCollection<string>());
      SetValue(NamesProperty, new ObservableCollection<string>());

      Groups.Add("Group1");
      Groups.Add("Group2");
      Names.Add("Name1");
      Names.Add("Name2");
      }

      public static readonly DependencyProperty GroupsProperty =
      DependencyProperty.Register("Groups", typeof(ObservableCollection<string>), typeof(MainWindow),
      new PropertyMetadata(null));

      public ObservableCollection<string> Groups
      {
      get { return (ObservableCollection<string>)GetValue(GroupsProperty); }
      set { SetValue(GroupsProperty, value); }
      }

      public static readonly DependencyProperty NamesProperty =
      DependencyProperty.Register("Names", typeof(ObservableCollection<string>), typeof(MainWindow),
      new PropertyMetadata(null));

      public ObservableCollection<string> Names
      {
      get { return (ObservableCollection<string>)GetValue(NamesProperty); }
      set { SetValue(NamesProperty, value); }
      }
      }


      Here is the result:



      enter image description here



      The first two rectangles are what ItemsControl generates. The third one is what I have manually added right after the ItemsControl. As you can see, even though the code is exactly the same in both cases, the first two rectangles don't have names, but the third one has. Is there any reason why wouldn't it work with ItemsControl?



      Edit:



      Here is the code of the MyUserControl.xaml.cs:



      public partial class MyUserControl : UserControl
      {
      public MyUserControl()
      {
      InitializeComponent();
      SetValue(NamesProperty, new ObservableCollection<string>());
      }

      public static readonly DependencyProperty NamesProperty = DependencyProperty.Register(
      "Names", typeof(ObservableCollection<string>), typeof(MyUserControl),
      new PropertyMetadata(null, NamesPropertyChanged));

      public ObservableCollection<string> Names
      {
      get { return (ObservableCollection<string>)GetValue(NamesProperty); }
      set { SetValue(NamesProperty, value); }
      }

      private static void NamesPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
      {
      var control = (MyUserControl)obj;
      var oldCollection = e.OldValue as INotifyCollectionChanged;
      var newCollection = e.NewValue as INotifyCollectionChanged;

      if (oldCollection != null)
      oldCollection.CollectionChanged -= control.NamesCollectionChanged;
      if (newCollection != null)
      newCollection.CollectionChanged += control.NamesCollectionChanged;

      control.UpdateNames();
      }

      private void NamesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
      {
      UpdateNames();
      }

      private void UpdateNames()
      {
      NamesPanel.Children.Clear();

      if (Names == null)
      return;

      foreach(var name in Names)
      {
      var textBlock = new TextBlock();
      textBlock.Text = name + ", ";
      NamesPanel.Children.Add(textBlock);
      }
      }
      }


      MyUserControl.xaml:



      <UserControl x:Class="TestItemsControl.MyUserControl"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:TestItemsControl"
      mc:Ignorable="d"
      d:DesignHeight="300"
      d:DesignWidth="300"
      Name="ParentControl">
      <StackPanel Name="NamesPanel" Orientation="Horizontal"/>
      </UserControl>






      c# wpf xaml data-binding






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 1 '16 at 16:59







      username

















      asked Dec 1 '16 at 16:35









      usernameusername

      1,93842652




      1,93842652
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Replace SetValue in the UserControl's constructor by SetCurrentValue. It may even make sense not to assign an initial value at all for the Names property.



          public MyUserControl()
          {
          InitializeComponent();
          SetCurrentValue(NamesProperty, new ObservableCollection<string>());
          }


          SetValue (as opposed to SetCurrentValue) sets a so-called local value to the Names property. When you assign a Binding as in the second case, this is also considered a local value with the same precedence as the one set in the constructor.



          However, in the first case, the Binding is set in a DataTemplate, where it doesn't count as a local value. Since it has lower precedence, it does not replace the initial value.



          More details here: Dependency Property Value Precedence






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40915818%2fcannot-bind-to-a-collection-from-itemscontrol-template%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            2














            Replace SetValue in the UserControl's constructor by SetCurrentValue. It may even make sense not to assign an initial value at all for the Names property.



            public MyUserControl()
            {
            InitializeComponent();
            SetCurrentValue(NamesProperty, new ObservableCollection<string>());
            }


            SetValue (as opposed to SetCurrentValue) sets a so-called local value to the Names property. When you assign a Binding as in the second case, this is also considered a local value with the same precedence as the one set in the constructor.



            However, in the first case, the Binding is set in a DataTemplate, where it doesn't count as a local value. Since it has lower precedence, it does not replace the initial value.



            More details here: Dependency Property Value Precedence






            share|improve this answer






























              2














              Replace SetValue in the UserControl's constructor by SetCurrentValue. It may even make sense not to assign an initial value at all for the Names property.



              public MyUserControl()
              {
              InitializeComponent();
              SetCurrentValue(NamesProperty, new ObservableCollection<string>());
              }


              SetValue (as opposed to SetCurrentValue) sets a so-called local value to the Names property. When you assign a Binding as in the second case, this is also considered a local value with the same precedence as the one set in the constructor.



              However, in the first case, the Binding is set in a DataTemplate, where it doesn't count as a local value. Since it has lower precedence, it does not replace the initial value.



              More details here: Dependency Property Value Precedence






              share|improve this answer




























                2












                2








                2







                Replace SetValue in the UserControl's constructor by SetCurrentValue. It may even make sense not to assign an initial value at all for the Names property.



                public MyUserControl()
                {
                InitializeComponent();
                SetCurrentValue(NamesProperty, new ObservableCollection<string>());
                }


                SetValue (as opposed to SetCurrentValue) sets a so-called local value to the Names property. When you assign a Binding as in the second case, this is also considered a local value with the same precedence as the one set in the constructor.



                However, in the first case, the Binding is set in a DataTemplate, where it doesn't count as a local value. Since it has lower precedence, it does not replace the initial value.



                More details here: Dependency Property Value Precedence






                share|improve this answer















                Replace SetValue in the UserControl's constructor by SetCurrentValue. It may even make sense not to assign an initial value at all for the Names property.



                public MyUserControl()
                {
                InitializeComponent();
                SetCurrentValue(NamesProperty, new ObservableCollection<string>());
                }


                SetValue (as opposed to SetCurrentValue) sets a so-called local value to the Names property. When you assign a Binding as in the second case, this is also considered a local value with the same precedence as the one set in the constructor.



                However, in the first case, the Binding is set in a DataTemplate, where it doesn't count as a local value. Since it has lower precedence, it does not replace the initial value.



                More details here: Dependency Property Value Precedence







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Dec 1 '16 at 17:09

























                answered Dec 1 '16 at 17:02









                ClemensClemens

                88.6k888176




                88.6k888176
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40915818%2fcannot-bind-to-a-collection-from-itemscontrol-template%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Lallio

                    Futebolista

                    Jornalista