Question


I was wandering if someone can explain to me how the Dependency Property DisplayMemberPath works? I am trying to create Custom ItemsControl that has property like DisplayMemberPath of a ComboBox, in otherwords after setting the ItemsSource I want to be able to specify the Property to Display.
At the moment if I do somthing like:

 <cc:MyControl ... DisplayMemberPath="MyObjectDescription" ... > 

(Yes I have overridden the DisplayMemberPath, its besides the point).

It displays a list of items, but they each Display "MyObjectDescription", instead of the value that that Property holds for each object in the ItemsSource. And I believe its because I am missing something in regards to how DisplayMemberPath Property works.
Thanks All. :)

Was it helpful?

Solution

There are two types of DisplayMemberPath. One that supports Binding and one where you have to set a string value. In your case as I can see you wish to implement the second one. To do so create a property inside your custom control of type string and name it DisplayMemberPath. Override the methode OnInitialized in your container with your custom logic where you tell the container to manipulate the path of the binding to DataContext by changing binding's path to the string value as you specified in DisplayMemeberPath. WPF calls OnInitalized once any control is completely initalized but before its about to get rendered. I hope this helps you any futher.

OTHER TIPS

I'm assuming your control is like MyControl and MyControlItem like ListBox and ListBoxItem. You can access the DisplayMemberPath of MyControl when the MyControlItem is being created and use it to get the data from the DataContext.

Bit late to party, but maybe other could be helped

If your purpose is barely to use Itemscontrol over ListBox/View, you may consider to define the Datatemplate for the itemscontrol's Items instead of packing this in a Usercontrol:

<ItemsControl ItemsSource="{Binding myObjectCollection}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding myObjectProp}"/> (or whatever...)
    </DataTemplate>
  </ItemsControl.ItemTemplate>
</ItemsControl>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top