firefly
firefly

Reputation: 285

How can I bind a property of a user control to a properties of that same control in WPF?

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.

Upvotes: 3

Views: 5199

Answers (2)

Lars Truijens
Lars Truijens

Reputation: 43595

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>

Upvotes: 10

Heinzi
Heinzi

Reputation: 172270

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

Upvotes: 2

Related Questions