Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. WPF
  4. DependancyProperty Confusion with Custom Controls and ModelView

DependancyProperty Confusion with Custom Controls and ModelView

Scheduled Pinned Locked Moved WPF
wpfcsharpwcfarchitecturehelp
16 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • P PaulPrice

    Afternoon Guys and Gals, I am trying to learn how to implement Custom Controls in WPF for use in a reusable controls library because I am not happy with the current implementation as our current method does not play well with MVVM. As an experiment I am trying to create a custom control that has two ListViews and two buttons, the idea being to allow a user to bind to SelectedItems and DeSelectItems properties in the view. These will populate the two list boxes from properties in a viewmodel. The buttons simply allowing the user to select an item and move it from one ListView to the other, ie selected / not selected. The problem I have is that when I bind to the SelectedItems and DeSelectedItems in xaml, neither dependancy property in the custom control actually get populates, ie the lists stay empty. I believe my mistake is related to Binding Source, something I do not understand so well The Custom Control Source - (The Test application is implemented as MVVM)

    namespace CustomControlLibrary
    {
    [TemplatePart(Name = DualListControl.ElementNotSelectedList, Type = typeof(ListView))]
    [TemplatePart(Name = DualListControl.ElementSelectedList, Type = typeof(ListView))]
    [TemplatePart(Name = DualListControl.ElementSelectButton, Type = typeof(Button))]
    [TemplatePart(Name = DualListControl.ElementDeselectButton, Type = typeof(Button))]
    public class DualListControl : Control
    {
    const string ElementNotSelectedList = "ElementNotSelectedList";
    const string ElementSelectedList = "ElementSelectedList";
    const string ElementSelectButton = "ElementSelectButton";
    const string ElementDeselectButton = "ElementDeselectButton";

        ListView \_NotSelectedList, \_SelectedList;
        Button \_SelectButton, \_DeselectButton;
        RelayCommand \_SelectItemCommand, \_DeSelectItemCommand;
    
        static DualListControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(DualListControl), new FrameworkPropertyMetadata(typeof(DualListControl)));
        }
    
        public DualListControl()
        {
            \_SelectItemCommand = new RelayCommand(p => SelectItemCommandExecute(), p => SelectItemCommandCanExecute);
            \_DeSelectItemCommand = new RelayCommand(p => DeSelectItemCommandExecute(), p => DeSelectItemCommandCanExecute);
        }
    
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
    
            \_NotSelectedList = GetTemplateChild(ElementNotSelectedLi
    
    I Offline
    I Offline
    Ian Shlasko
    wrote on last edited by
    #2

    I think I see your problem. You guessed right... Your binding sources aren't set. By default, the binding source is the DataContext, and that's not what you want here. Since those bindings are inside the control template, you want to bind to the "TemplatedParent" (It's one of the options for RelativeSource).

    ItemsSource="{Binding Path=SelectedItems,RelativeSource={RelativeSource TemplatedParent}}"

    Even easier, though... There's a shortcut for that, which does exactly the same thing...

    ItemsSource="{TemplateBinding SelectedItems}"

    Proud to have finally moved to the A-Ark. Which one are you in?
    Author of the Guardians Saga (Sci-Fi/Fantasy novels)

    P 1 Reply Last reply
    0
    • I Ian Shlasko

      I think I see your problem. You guessed right... Your binding sources aren't set. By default, the binding source is the DataContext, and that's not what you want here. Since those bindings are inside the control template, you want to bind to the "TemplatedParent" (It's one of the options for RelativeSource).

      ItemsSource="{Binding Path=SelectedItems,RelativeSource={RelativeSource TemplatedParent}}"

      Even easier, though... There's a shortcut for that, which does exactly the same thing...

      ItemsSource="{TemplateBinding SelectedItems}"

      Proud to have finally moved to the A-Ark. Which one are you in?
      Author of the Guardians Saga (Sci-Fi/Fantasy novels)

      P Offline
      P Offline
      PaulPrice
      wrote on last edited by
      #3

      Ian, Firstly, thanks for taking the time to look. I have tried your suggestion and it has not yet resolved the problem, I do believe however that you have got me somewhat closer. While trying this out, I notice that the actual dependancy properties SelectedItems and DeSelectedItems on the DualListControl class are not being set by the bindings, ie they are empty lists even though they shold (as far as I understand) be the same lists as thoose specified in the MainAppView. With my test data, I am expecting the DualListControl.DeSelectedItems to contain the items "One", "Two", "Three", "Four" if you see what I mean. Any ideas? Paul

      Just racking up the postings

      I 1 Reply Last reply
      0
      • P PaulPrice

        Ian, Firstly, thanks for taking the time to look. I have tried your suggestion and it has not yet resolved the problem, I do believe however that you have got me somewhat closer. While trying this out, I notice that the actual dependancy properties SelectedItems and DeSelectedItems on the DualListControl class are not being set by the bindings, ie they are empty lists even though they shold (as far as I understand) be the same lists as thoose specified in the MainAppView. With my test data, I am expecting the DualListControl.DeSelectedItems to contain the items "One", "Two", "Three", "Four" if you see what I mean. Any ideas? Paul

        Just racking up the postings

        I Offline
        I Offline
        Ian Shlasko
        wrote on last edited by
        #4

        Guess we only fixed half of the problem then... Now the template should be properly bound to the parent control, but are the parent control's properties actually binding to a MainAppViewModel? Somewhere in your window code (Or wherever the MainAppView control is contained), you need to set the DataContext to a MainAppViewModel... Otherwise, the control has nothing to bind to.

        Proud to have finally moved to the A-Ark. Which one are you in?
        Author of the Guardians Saga (Sci-Fi/Fantasy novels)

        P 1 Reply Last reply
        0
        • I Ian Shlasko

          Guess we only fixed half of the problem then... Now the template should be properly bound to the parent control, but are the parent control's properties actually binding to a MainAppViewModel? Somewhere in your window code (Or wherever the MainAppView control is contained), you need to set the DataContext to a MainAppViewModel... Otherwise, the control has nothing to bind to.

          Proud to have finally moved to the A-Ark. Which one are you in?
          Author of the Guardians Saga (Sci-Fi/Fantasy novels)

          P Offline
          P Offline
          PaulPrice
          wrote on last edited by
          #5

          Unfortunatly this is already done. I have double checked and I can see while debugging that both the MainAppView and the DualListControl instance have the DataContext set to the same instance of the MainAppViewModel class. The Content of the main window is set as follows

          public MainWindow()
          {
              InitializeComponent();
              Content = new MainAppViewModel();
          }
          

          And in the App.xaml i have a DataTemplate telling WPF how to render the object as follows

          <Application x:Class="TestApplication.App"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:ViewModels="clr-namespace:TestApplication.ViewModels"
          xmlns:Views="clr-namespace:TestApplication.Views"
          StartupUri="MainWindow.xaml">
          <Application.Resources>
          <DataTemplate DataType="{x:Type ViewModels:MainAppViewModel}">
          Views:MainAppView/
          </DataTemplate>
          </Application.Resources>
          </Application>

          If you see what I mean So the part that is missing is the actual binding of the DualListControls dependancy properties being bound to the MainAppViewModels SelectedListA and DeSelectedListA properties. Any ideas as to what I have missed?

          Just racking up the postings

          I S 2 Replies Last reply
          0
          • P PaulPrice

            Afternoon Guys and Gals, I am trying to learn how to implement Custom Controls in WPF for use in a reusable controls library because I am not happy with the current implementation as our current method does not play well with MVVM. As an experiment I am trying to create a custom control that has two ListViews and two buttons, the idea being to allow a user to bind to SelectedItems and DeSelectItems properties in the view. These will populate the two list boxes from properties in a viewmodel. The buttons simply allowing the user to select an item and move it from one ListView to the other, ie selected / not selected. The problem I have is that when I bind to the SelectedItems and DeSelectedItems in xaml, neither dependancy property in the custom control actually get populates, ie the lists stay empty. I believe my mistake is related to Binding Source, something I do not understand so well The Custom Control Source - (The Test application is implemented as MVVM)

            namespace CustomControlLibrary
            {
            [TemplatePart(Name = DualListControl.ElementNotSelectedList, Type = typeof(ListView))]
            [TemplatePart(Name = DualListControl.ElementSelectedList, Type = typeof(ListView))]
            [TemplatePart(Name = DualListControl.ElementSelectButton, Type = typeof(Button))]
            [TemplatePart(Name = DualListControl.ElementDeselectButton, Type = typeof(Button))]
            public class DualListControl : Control
            {
            const string ElementNotSelectedList = "ElementNotSelectedList";
            const string ElementSelectedList = "ElementSelectedList";
            const string ElementSelectButton = "ElementSelectButton";
            const string ElementDeselectButton = "ElementDeselectButton";

                ListView \_NotSelectedList, \_SelectedList;
                Button \_SelectButton, \_DeselectButton;
                RelayCommand \_SelectItemCommand, \_DeSelectItemCommand;
            
                static DualListControl()
                {
                    DefaultStyleKeyProperty.OverrideMetadata(typeof(DualListControl), new FrameworkPropertyMetadata(typeof(DualListControl)));
                }
            
                public DualListControl()
                {
                    \_SelectItemCommand = new RelayCommand(p => SelectItemCommandExecute(), p => SelectItemCommandCanExecute);
                    \_DeSelectItemCommand = new RelayCommand(p => DeSelectItemCommandExecute(), p => DeSelectItemCommandCanExecute);
                }
            
                public override void OnApplyTemplate()
                {
                    base.OnApplyTemplate();
            
                    \_NotSelectedList = GetTemplateChild(ElementNotSelectedLi
            
            S Offline
            S Offline
            SledgeHammer01
            wrote on last edited by
            #6
            1. First issue I see is that your dependency properties are set up incorrectly. Think about whats happening here... SelectedItemsProperty and DeSelectedItemsProperty are static (meaning a single instance in this case). You have set the values to new ObservableCollection(). What you end up with is *EVERY* DualListControl in the world is using the same ObservableCollection(). You also allow users to overwrite the collections completely. Not something you want to do. Use DependencyProperty.RegisterReadOnly() to register the property as a read-only DP and create the ObservableCollection() in the public DualListControl() constructor. Something like: public DualListControl() { SetValue(SelectedItemsPropertyKey, new ObservableCollection()); } then remove the setters for those properties. 2) Bindings in generic.xaml should be TemplateBinding, not binding.
            P 1 Reply Last reply
            0
            • S SledgeHammer01
              1. First issue I see is that your dependency properties are set up incorrectly. Think about whats happening here... SelectedItemsProperty and DeSelectedItemsProperty are static (meaning a single instance in this case). You have set the values to new ObservableCollection(). What you end up with is *EVERY* DualListControl in the world is using the same ObservableCollection(). You also allow users to overwrite the collections completely. Not something you want to do. Use DependencyProperty.RegisterReadOnly() to register the property as a read-only DP and create the ObservableCollection() in the public DualListControl() constructor. Something like: public DualListControl() { SetValue(SelectedItemsPropertyKey, new ObservableCollection()); } then remove the setters for those properties. 2) Bindings in generic.xaml should be TemplateBinding, not binding.
              P Offline
              P Offline
              PaulPrice
              wrote on last edited by
              #7

              SledgeHammer, Thanks for your time and comments Re point one, DependancyProperties obviously still confuse the life out of me! I tried making this a readonly collection and then realised what you are suggesting, you have given me the method required if I want a single list for all DualListControls right? but these can no longer be ovverriden by a user. That is not my intention, what I am trying to achieve and failing is to be allow a developer to do something like this

              <Grid>
                  <CustomControls:DualListControl Name="List" SelectedItems="{Binding SelectedItemsA}" DeSelectedItems="{Binding DeslectedItemsA}"/>
              </Grid>
              

              The problem I appear to have is that the SelectedItems dependancy property is not being bound to the one in the MainAppViewModel. Re point two, Ian has already found this and corrected me, the bindings in the Generic.xaml are now as the follows

              <ListView Grid.Column="2" Name="ElementSelectedList" ItemsSource="{TemplateBinding SelectedItems}"/>

              Have I understood this correctly?

              Just racking up the postings

              S 1 Reply Last reply
              0
              • P PaulPrice

                Unfortunatly this is already done. I have double checked and I can see while debugging that both the MainAppView and the DualListControl instance have the DataContext set to the same instance of the MainAppViewModel class. The Content of the main window is set as follows

                public MainWindow()
                {
                    InitializeComponent();
                    Content = new MainAppViewModel();
                }
                

                And in the App.xaml i have a DataTemplate telling WPF how to render the object as follows

                <Application x:Class="TestApplication.App"
                xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:ViewModels="clr-namespace:TestApplication.ViewModels"
                xmlns:Views="clr-namespace:TestApplication.Views"
                StartupUri="MainWindow.xaml">
                <Application.Resources>
                <DataTemplate DataType="{x:Type ViewModels:MainAppViewModel}">
                Views:MainAppView/
                </DataTemplate>
                </Application.Resources>
                </Application>

                If you see what I mean So the part that is missing is the actual binding of the DualListControls dependancy properties being bound to the MainAppViewModels SelectedListA and DeSelectedListA properties. Any ideas as to what I have missed?

                Just racking up the postings

                I Offline
                I Offline
                Ian Shlasko
                wrote on last edited by
                #8

                Pardon the slow response... Busy busy... Anyway... I'm running out of ideas here... Have you checked for any reported data binding errors? They don't pop up as exceptions, but if you bring up the Output window in your IDE, they should show up there.

                Proud to have finally moved to the A-Ark. Which one are you in?
                Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                1 Reply Last reply
                0
                • P PaulPrice

                  SledgeHammer, Thanks for your time and comments Re point one, DependancyProperties obviously still confuse the life out of me! I tried making this a readonly collection and then realised what you are suggesting, you have given me the method required if I want a single list for all DualListControls right? but these can no longer be ovverriden by a user. That is not my intention, what I am trying to achieve and failing is to be allow a developer to do something like this

                  <Grid>
                      <CustomControls:DualListControl Name="List" SelectedItems="{Binding SelectedItemsA}" DeSelectedItems="{Binding DeslectedItemsA}"/>
                  </Grid>
                  

                  The problem I appear to have is that the SelectedItems dependancy property is not being bound to the one in the MainAppViewModel. Re point two, Ian has already found this and corrected me, the bindings in the Generic.xaml are now as the follows

                  <ListView Grid.Column="2" Name="ElementSelectedList" ItemsSource="{TemplateBinding SelectedItems}"/>

                  Have I understood this correctly?

                  Just racking up the postings

                  S Offline
                  S Offline
                  SledgeHammer01
                  wrote on last edited by
                  #9

                  No, what you have *NOW* will result in every DualListControl sharing the same ObservableCollection instance. I'll assume that you want each one to have its own. The solution I gave you will give each instance its own collection. The UserControl doesn't have its DataContext set, so those Binding will not work. The bindings in Generic.xaml should be TemplateBinding.

                  P 1 Reply Last reply
                  0
                  • P PaulPrice

                    Unfortunatly this is already done. I have double checked and I can see while debugging that both the MainAppView and the DualListControl instance have the DataContext set to the same instance of the MainAppViewModel class. The Content of the main window is set as follows

                    public MainWindow()
                    {
                        InitializeComponent();
                        Content = new MainAppViewModel();
                    }
                    

                    And in the App.xaml i have a DataTemplate telling WPF how to render the object as follows

                    <Application x:Class="TestApplication.App"
                    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:ViewModels="clr-namespace:TestApplication.ViewModels"
                    xmlns:Views="clr-namespace:TestApplication.Views"
                    StartupUri="MainWindow.xaml">
                    <Application.Resources>
                    <DataTemplate DataType="{x:Type ViewModels:MainAppViewModel}">
                    Views:MainAppView/
                    </DataTemplate>
                    </Application.Resources>
                    </Application>

                    If you see what I mean So the part that is missing is the actual binding of the DualListControls dependancy properties being bound to the MainAppViewModels SelectedListA and DeSelectedListA properties. Any ideas as to what I have missed?

                    Just racking up the postings

                    S Offline
                    S Offline
                    SledgeHammer01
                    wrote on last edited by
                    #10

                    You need to set the DataContext on your View to point to your model.

                    I 1 Reply Last reply
                    0
                    • S SledgeHammer01

                      You need to set the DataContext on your View to point to your model.

                      I Offline
                      I Offline
                      Ian Shlasko
                      wrote on last edited by
                      #11

                      No, he has that part right, I believe... He's using a DataTemplate, so it goes like this: 1) MainWindow has its Content set to the model 2) Content is rendered using a DataTemplate which contains a MainAppView (If this failed, he wouldn't see his control at all) 3) MainAppView, being inside a DataTemplate, uses that model as its DataContext 4) MainAppView contains a DualListControl, with its SelectedItems and DeselectedItems properties bound to that model 5) DualListControl is rendered using a DataTemplate, which contains two ListViews that are template-bound to those properties It's a bit more indirect than I would have done, but it should work. #1 and #2 are solid... #3 is what you're talking about, but that should happen automatically. #5 is the TemplateBinding thing he already fixed... I think the broken link is in #4, just by process of elimination, but I don't see the actual problem.

                      Proud to have finally moved to the A-Ark. Which one are you in?
                      Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                      S P 2 Replies Last reply
                      0
                      • I Ian Shlasko

                        No, he has that part right, I believe... He's using a DataTemplate, so it goes like this: 1) MainWindow has its Content set to the model 2) Content is rendered using a DataTemplate which contains a MainAppView (If this failed, he wouldn't see his control at all) 3) MainAppView, being inside a DataTemplate, uses that model as its DataContext 4) MainAppView contains a DualListControl, with its SelectedItems and DeselectedItems properties bound to that model 5) DualListControl is rendered using a DataTemplate, which contains two ListViews that are template-bound to those properties It's a bit more indirect than I would have done, but it should work. #1 and #2 are solid... #3 is what you're talking about, but that should happen automatically. #5 is the TemplateBinding thing he already fixed... I think the broken link is in #4, just by process of elimination, but I don't see the actual problem.

                        Proud to have finally moved to the A-Ark. Which one are you in?
                        Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                        S Offline
                        S Offline
                        SledgeHammer01
                        wrote on last edited by
                        #12

                        Well, its a retarded way to do it and he should unretard it. Not make it more retarded :). If he did it the correct way, he wouldn't be trouble shooting wacky issues. Oh wellz :).

                        P 1 Reply Last reply
                        0
                        • S SledgeHammer01

                          No, what you have *NOW* will result in every DualListControl sharing the same ObservableCollection instance. I'll assume that you want each one to have its own. The solution I gave you will give each instance its own collection. The UserControl doesn't have its DataContext set, so those Binding will not work. The bindings in Generic.xaml should be TemplateBinding.

                          P Offline
                          P Offline
                          PaulPrice
                          wrote on last edited by
                          #13

                          SledgeHammer, I appreciate your time. I understand your point about a single list instance being shared amongst all controls. Please understand that I have been making changes as recommended by yourself and Ian (above). The complication that arises with the ReadOnly method you describe is that I would like to be able to allow the consumer to use the control in the following way. The ReadOnly method does not allow me to do this. Any suggestions?

                              <CustomControls:DualListControl SelectedItems="{Binding SelectedItemsA}" DeSelectedItems="{Binding DeSelectedItemsA}" Width="300" Height="300"/>
                          

                          Regarding the DataContext, the control template does not appear to require the DataContext specifically set as the ViewModel is implicitly bound to the parent view and therefore to this control, I have verified this while debugging. I do have the control working as intended but only tested as a single instance at the moment, I will test with mutiple instances to enable me to fix the single list instance issue you have kindly pointed out. Once again, thanks for your time.

                          Just racking up the postings

                          S 1 Reply Last reply
                          0
                          • I Ian Shlasko

                            No, he has that part right, I believe... He's using a DataTemplate, so it goes like this: 1) MainWindow has its Content set to the model 2) Content is rendered using a DataTemplate which contains a MainAppView (If this failed, he wouldn't see his control at all) 3) MainAppView, being inside a DataTemplate, uses that model as its DataContext 4) MainAppView contains a DualListControl, with its SelectedItems and DeselectedItems properties bound to that model 5) DualListControl is rendered using a DataTemplate, which contains two ListViews that are template-bound to those properties It's a bit more indirect than I would have done, but it should work. #1 and #2 are solid... #3 is what you're talking about, but that should happen automatically. #5 is the TemplateBinding thing he already fixed... I think the broken link is in #4, just by process of elimination, but I don't see the actual problem.

                            Proud to have finally moved to the A-Ark. Which one are you in?
                            Author of the Guardians Saga (Sci-Fi/Fantasy novels)

                            P Offline
                            P Offline
                            PaulPrice
                            wrote on last edited by
                            #14

                            Ian, You are correct in the way DataContext is set. I am using a method learned from one of the MVVM mechanism described on a tutorial published in CodeProject, I forget the Authors name right now, search WPF MVVM. As mentioned in another comment, I do somehow have this working and will publish my fixes here when I have got close to understanding how I fixed it. Something to do wth the MetaData part and creating an instance of the list in the constructor. Like I said, I will put my changes up as soon as I can. I also appreciate that I may have a single list instance issue as mentioned by SledgeHammer. Again, thanks for your time, there is nothing worse than head butting a brick wall.

                            Just racking up the postings

                            1 Reply Last reply
                            0
                            • S SledgeHammer01

                              Well, its a retarded way to do it and he should unretard it. Not make it more retarded :). If he did it the correct way, he wouldn't be trouble shooting wacky issues. Oh wellz :).

                              P Offline
                              P Offline
                              PaulPrice
                              wrote on last edited by
                              #15

                              Concerning the Retaded way this is done, can you elaborate? I am not sure I understand what you think is wrong with my MVVM implementation. I am not shooting or getting upset, please do not misread my comment in that way, I am only trying to learn. All of the source code is available above. How would you achieve MVVM?

                              Just racking up the postings

                              1 Reply Last reply
                              0
                              • P PaulPrice

                                SledgeHammer, I appreciate your time. I understand your point about a single list instance being shared amongst all controls. Please understand that I have been making changes as recommended by yourself and Ian (above). The complication that arises with the ReadOnly method you describe is that I would like to be able to allow the consumer to use the control in the following way. The ReadOnly method does not allow me to do this. Any suggestions?

                                    <CustomControls:DualListControl SelectedItems="{Binding SelectedItemsA}" DeSelectedItems="{Binding DeSelectedItemsA}" Width="300" Height="300"/>
                                

                                Regarding the DataContext, the control template does not appear to require the DataContext specifically set as the ViewModel is implicitly bound to the parent view and therefore to this control, I have verified this while debugging. I do have the control working as intended but only tested as a single instance at the moment, I will test with mutiple instances to enable me to fix the single list instance issue you have kindly pointed out. Once again, thanks for your time.

                                Just racking up the postings

                                S Offline
                                S Offline
                                SledgeHammer01
                                wrote on last edited by
                                #16

                                Ok... So, what you are initially doing is having every instance of your control share the same instance of ObservableCollection. However, you do allow the user to overwrite said instance through your property setter. That will cause you *many* problems down the road with data binding. One area where WPF crumbles hard is when you start switching around instances of objects or creating temporary objects, etc. because it depends on those being the same object to function. Now, C# doesn't have pointers, but I will use them to illustrate what I am trying to explain. 1) you create your control, your control creates an ObservableCollection() [0x1000] 2) a user of your control subscribes to [0x1000].CollectionChanges 3) a user calls your setter with a new ObservableCollection() [0x2000] Guess what happened? Everybody subscribing to the [0x1000] collection events is now broken. Everybody making changes to the [0x1000] collection is broken as well. [0x1000] is now orphaned. What you want is for each instance of your control to create its own ObservableCollection and *NEVER* let anybody change that. It is important that if you created [0x1000], that it remains [0x1000] for the lifetime of your control. Otherwise bad things will happen. Now, the read-only DP will not fulfil your just mentioned requirement of binding to collections. Fair enough. What you are trying to do here is combining TWO techniques into ONE which will cause you the problems just mentioned. If you look at the ListView or TreeView for example, you will see the proper way to lay out your control. public ObservableCollection Items // this *MUST* be read-only { get { ... } } public IEnumerable ItemsSource /// this is how people will pass in collections { get { ... } set { ... } } So what happens here is that people can add items manually to the Items collection OR use the ItemsSource to pass in collections. If you only need to allow passing in collections, use the IEnumerable ItemsSource method instead. If you want to support both, you need to add some "protection" code... i.e. don't allow use of Items if ItemsSource is not null and vice versa, etc.

                                1 Reply Last reply
                                0
                                Reply
                                • Reply as topic
                                Log in to reply
                                • Oldest to Newest
                                • Newest to Oldest
                                • Most Votes


                                • Login

                                • Don't have an account? Register

                                • Login or register to search.
                                • First post
                                  Last post
                                0
                                • Categories
                                • Recent
                                • Tags
                                • Popular
                                • World
                                • Users
                                • Groups