绑定XAML中Itemscontrol之外的Property

我试图绑定一个在Itemscontrol之外的Property。 然而,这似乎不起作用。

似乎在ItemsControl中,DataTemplate指的是集合内部而不是它之外的内容。 我已尝试使用RelativeResource并为ViewModel引用了AncestorType。

代码(VM):

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

XAML(查看):

     

您需要绑定到父ItemsControlDataContext

     

我在这个问题上做了一个快速而完整的例子:

                  

每行的上下文设置为绑定列表中的每个对象。 在我们的例子中,从items集合到每个Model实例。

要返回父级的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 items { get; set; } public MainWindow() { InitializeComponent(); items = new ObservableCollection(); 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上定义的属性。

在此处输入图像描述