I’m trying to implement a visual Form Designer in WPF. I’ve got a Canvas where the user can drag ‘n drop some Controls (Textbox, Textblock, Combobox, Checkbox, Image, Button) on. So far so good. Now I’m trying to implement a combobox wich lists all Controls the user has put on the canvas (like VS 2008 does).
The combobox displays the Name Property of the control. It works good for all Controls except Buttons and Checkboxes and I can’t figure out why. The Combobox is bound to a ObservableCollection and the Item Collection of the Combobox is filled correct but when I select a Button or Checkbox the Name is not displayed as SelectedItem. So here is my Binding:
<ComboBox Name="comboBoxCurrentControls" IsEditable="false"
ItemsSource="{Binding AllFormControls}" DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedItem="{Binding Path=SelectedCtl, Mode=TwoWay}"
You can reproduce the problem when you simple fill a ObservableCollection<T> in Codebehind with Buttons and bind a Combobox on it. The Combobox will not show a Button’s Name as SelectedItem when you select it.
Can someone explain me this behavior or tell me a workaround for this!?
Thanks in advance
Chris
P.s: I also tried to use ObservableCollection<FrameworkElement> but it didn’t help.
The problem is that Button is a ContentControl so when the button is selected, the ComboBox’s SelectionBoxItem uses the Content property rather than the Button itself. With the given bindings it’s then trying to find the Name property on the content (which I imagine was a string?). This can be discovered by looking at the output for binding errors. You should see something like:
System.Windows.Data Error: 40 : BindingExpression path error: ‘Name’ property not found on ‘object’ ”String’ (HashCode=1231357559)’. BindingExpression:Path=Name; DataItem=’String’ (HashCode=1231357559); target element is ‘TextBlock’ (Name=”); target property is ‘Text’ (type ‘String’)
If you use Snoop, when you click the Button, you’ll see that the SelectionBoxItem is the button content, whereas when you select a different control it is the Control itself.
Edit : With a little googling, I came across this: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7054a9c9-fec1-463a-9568-b831729acd14