Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind a Property that is outside of an Itemscontrol in XAML

I am trying to bind a Property that is outside of an Itemscontrol. However that doesn't seem to work.

It seems that in ItemsControl, DataTemplate it refers to what is inside of the collection and not outside of it. I have tried with RelativeResource and Referred to AncestorType for the ViewModel.

Code (VM):

public class Test {
  public string GetThis {get{return "123";} set{}}
  public List<string> IterateProperty {get; set;}
}

XAML (View):

<ItemsControl ItemsSource="{Binding Path=IterateProperty}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="I want to bind the string property GetThis!" />
like image 318
Khiem-Kim Ho Xuan Avatar asked Jun 18 '15 13:06

Khiem-Kim Ho Xuan


1 Answers

You need to bind to the DataContext of the parent ItemsControl.

<ItemsControl ItemsSource="{Binding Path=IterateProperty}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{Binding DataContext.GetThis,
                                RelativeSource={RelativeSource Mode=FindAncestor,
                                                               AncestorType={x:Type ItemsControl}}}" />
like image 88
Mike Eason Avatar answered Sep 18 '22 12:09

Mike Eason