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开发者_JAVA技巧
<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.
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>
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
精彩评论