views:

56

answers:

2

Inside my user control I have a collection call Solutions

 public List<string> Solutions { get; set; }

I want to bind that property to a combobox in xaml of that same user control?

I tried

<ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194" Height="21" VerticalAlignment="Bottom" 
              ItemsSource="{Binding Path=Solutions}"    />

but that didn't seem to work.

+1  A: 

Move the XAML of your control into the Template property, i.e. instead of

<UserControl x:Class="MyUserControl" ...>
    ...
    <ComboBox ... />
    ...
</UserControl>

use

<UserControl x:Class="MyUserControl" ...>
    <UserControl.Template>
        <ControlTemplate>
            ...
            <ComboBox ... />
            ...
        </ControlTemplate>
    </UserControl.Template>
</UserControl>

Then, you can use TemplateBinding:

            <ComboBox ... ItemsSource="{TemplateBinding Solutions}" />

BTW, your question is very similar to this one: Custom UserControl Property used by child element

Heinzi
This look interesting, but it require that Solutions have to be static. Is there a way around that?
firefly
Actually, no, `Solutions` doesn't need to be static. (At least it works for me without being static...)
Heinzi
Hmmm.. I tried and it give me that error when I build the solution. Perhaps I missed something. Will have to try again next time.
firefly
+3  A: 

Name your UserControl in XAML and refer to it from the binding like so:

<UserControl x:Name = "MyUserControl">
  <ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194"
            Height="21" VerticalAlignment="Bottom" 
            ItemsSource="{Binding ElementName=MyUserControl, Path=Solutions}" />
</UserControl>

If you want proper binding your UserControl should implement INotifyPropertyChanged for that property or make that property a Dependency Property

Update

Or use RelativeSource if you don't want to name the UserControl

<UserControl>
  <ComboBox HorizontalAlignment="Left" Margin="21,0,0,41" Name="cbAddSolution" Width="194"
            Height="21" VerticalAlignment="Bottom" 
            ItemsSource="{Binding Path=Solutions, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</UserControl>
Lars Truijens
This work nicely, thank you. I know about the ElementName before. But I thought it can only be used to refer to another element, I didn't know a class in XAML can name itself... that's new to me.
firefly
I wonder is there a away for an object to refer to itself without a name, something like "this" in code...
firefly
Updated the answer with a way to do it without a name
Lars Truijens
Thanks for the addition. I've look at RelativeSource too but it wasn't too intuitive. I would thought something like "Self" would make sense. But it seem that what they are doing is walking up the hierarchy starting from self... by using AncestorType.
firefly