简体   繁体   English

绑定XAML中ItemsControl之外的属性

[英]Bind a Property that is outside of an Itemscontrol in XAML

I am trying to bind a Property that is outside of an Itemscontrol. 我正在尝试绑定ItemsControl之外的Property。 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. 似乎在ItemsControl中,DataTemplate引用的是集合内部的内容,而不是集合外部的内容。 I have tried with RelativeResource and Referred to AncestorType for the ViewModel. 我已经尝试过使用RelativeResource并为ViewModel引用AncestorType。

Code (VM): 代码(VM):

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

XAML (View): XAML(视图):

<ItemsControl ItemsSource="{Binding Path=IterateProperty}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="I want to bind the string property GetThis!" />

You need to bind to the DataContext of the parent ItemsControl . 您需要绑定到父ItemsControlDataContext

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

I've made a fast and full example on this : 我对此做了一个快速而完整的例子:

<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>

The context for each row is set to each object from the bound list. 将每一行的上下文设置为绑定列表中的每个对象。 In our case, to each Model instance from the items collection. 在我们的例子中,从items集合到每个Model实例。

To go back to the parent's DataContext this syntax is used: 返回到父级的DataContext,使用以下语法:

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

Here is the codebehind: 下面是代码:

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;
    }
}

You can define your dependency property in your ViewModel. 您可以在ViewModel中定义依赖项属性。

And here is my simple Model: 这是我的简单模型:

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 { };
}

As a result, you can access the property defined on your parent's DataContext. 结果,您可以访问在父级的DataContext上定义的属性。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM