2015-06-18 3 views
7

Я пытаюсь связать свойство, находящееся за пределами элемента управления Itemscontrol. Однако это не работает.Привязать свойство, находящееся за пределами элемента управления Items в XAML

Кажется, что в ItemsControl DataTemplate это относится к тому, что находится внутри коллекции, а не за ее пределами. Я пробовал с RelativeResource и ссылался на AncestorType для ViewModel.

Код (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!" /> 
+0

Вы можете проверить мой пример о том, как определить свои свойства? Это может быть полезно. –

ответ

8

Вы должны связываться с DataContext родителя ItemsControl.

<ItemsControl ItemsSource="{Binding Path=IterateProperty}"> 
    <ItemsControl.ItemTemplate> 
    <DataTemplate> 
     <TextBlock Text="{Binding DataContext.GetThis, 
           RelativeSource={RelativeSource Mode=FindAncestor, 
                   AncestorType={x:Type ItemsControl}}}" /> 
+0

hmm good pinpoint, но я все еще получаю сообщение об ошибке. Но теперь он говорит: «Невозможно разрешить свойство« ... »в контексте данных типа« System.Windows.Controls.ItemsControl »nooooo :( –

+0

Неплохо, я отредактировал код, повторите попытку. –

+0

кажется, что я все еще получаю ту же самую проблему. Я использую калибраторы MVVM (извините, забыл упомянуть об этом тоже) –

3

Я сделал быстрый и полный пример на этом:

<Window x:Class="ParentDataContext.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <DataGrid ItemsSource="{Binding items}" AutoGenerateColumns="False"> 
     <DataGrid.Columns> 
      <DataGridTemplateColumn> 
       <DataGridTemplateColumn.CellTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal"> 
          <CheckBox IsChecked="{Binding IsChecked}"></CheckBox> 
          <TextBlock Margin="5" 
             Text="{Binding Path=DataContext.TextFromParent,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/> 
         </StackPanel> 
        </DataTemplate> 
       </DataGridTemplateColumn.CellTemplate> 
      </DataGridTemplateColumn> 
     </DataGrid.Columns> 
    </DataGrid> 
</Grid> 

Контекст для каждой строки устанавливается для каждого объекта из связанного списка. В нашем случае для каждого экземпляра модели из коллекции элементов.

Чтобы вернуться к родительской DataContext используется этот синтаксис:

Text="{Binding Path=DataContext.TextFromParent,RelativeSource={RelativeSource AncestorType={x:Type Window}}}"/> 

Вот отделенный код:

public partial class MainWindow : Window 
{ 
    public string TextFromParent 
    { 
     get { return (string)GetValue(TextFromParentProperty); } 
     set { SetValue(TextFromParentProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for TextFromParent. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty TextFromParentProperty = 
     DependencyProperty.Register("TextFromParent", typeof(string), typeof(MainWindow), new PropertyMetadata(string.Empty)); 


    public ObservableCollection<Model> items { get; set; } 
    public MainWindow() 
    { 
     InitializeComponent(); 
     items = new ObservableCollection<Model>(); 
     items.Add(new Model() { IsChecked = true }); 
     items.Add(new Model() { IsChecked = false }); 
     items.Add(new Model() { IsChecked = true }); 
     items.Add(new Model() { IsChecked = false }); 
     TextFromParent = "test"; 
     this.DataContext = this; 
    } 
} 

Вы можете определить свойство зависимостей в вашей ViewModel.

А вот моя простая модель:

public class Model : INotifyPropertyChanged 
{ 
    private bool _IsChecked; 

    public bool IsChecked 
    { 
     get { return _IsChecked; } 
     set 
     { 
      _IsChecked = value; 
      PropertyChanged(this, new PropertyChangedEventArgs("IsChecked")); 
     } 
    } 

    public event PropertyChangedEventHandler PropertyChanged = delegate { }; 
} 

В результате, вы можете получить доступ к собственности, определенный на своих родителей DataContext.

enter image description here

+0

Спасибо, брат. Это помогло –

Смежные вопросы