18 September 2011

WPF - Bind to a property in code-behind

In some case, like when you have a ComboBox inside a DataTemplate, you can't set a property, the ItemsSource in this case, from code-behind. You have to use a binding to set this property, and you can like this:

In code-behind, create a public property and set that instead:
public BindingList ProductList { get; private set; }

Then use a binding to that property to set the property of the element:
<DataTemplate>
  <this:ComboBox
        ItemsSource="{Binding ProductList,
        RelativeSource={RelativeSource  Mode=FindAncestor,
        AncestorType={x:Type this:ucStoreVisit}}}" />
</DataTemplate>

And it'll work!

No comments:

Post a Comment