内部ItemsControl中对象的属性如何绑定到外部ItemsControl中对象的属性?

时间:2011-11-22 21:45:11

标签: c# wpf binding itemscontrol

标题可能听起来很复杂,但请耐心等待。

我有包含住户的房间:

public class Room
{
    public string Name { get; set; }
    public List<Person> Occupants { get; set; }
    public bool AreOccupantsEditable { get; set; }
}

public class Person
{
    public string Name { get; set; }
}

这是一系列房间:

<ResourceDictionary>
    <x:Array x:Key="Rooms" Type="local:Room">
        <local:Room Name="Happy Room" AreOccupantsEditable="True">
            <local:Room.Occupants>
                <local:Person Name="Mindy" />
            </local:Room.Occupants>
        </local:Room>
        <local:Room Name="Sad Room" AreOccupantsEditable="True">
            <local:Room.Occupants>
                <local:Person Name="Bob" />
                <local:Person Name="Jane" />
            </local:Room.Occupants>
        </local:Room>
        <local:Room Name="Kill Room" AreOccupantsEditable="False">
            <local:Room.Occupants>
                <local:Person Name="Mork" />
                <local:Person Name="Dave" />
                <local:Person Name="Ryan" />
            </local:Room.Occupants>
        </local:Room>
    </x:Array>
</ResourceDictionary>

这是ItemsControl中的ItemsControl,用于显示房间及其占用者:

<ItemsControl ItemsSource="{Binding Source={StaticResource Rooms}}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <!-- room name -->
                <TextBlock Text="{Binding Path=Name}" />
                <ItemsControl ItemsSource="{Binding Path=Occupants}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <!-- occupant name -->
                            <TextBox Text="{Binding Path=Name}" Margin="20,0,0,0" IsEnabled="{Binding ???}" />
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

如果没有Person引用Room,我如何将TextBox的IsEnabled属性绑定到Person所在的Room的AreOccupantsEditable属性?

如果有帮助,这是一个示例项目:http://dl.dropbox.com/u/4220513/ItemsControl-Binding.zip

2 个答案:

答案 0 :(得分:3)

您可以使用RelativeSource访问外部DataContext

IsEnabled="{Binding Path=DataContext.AreOccupantsEditable, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"

答案 1 :(得分:0)

你也可以使用Occupants的itemsControl的IsEnabled属性来禁用整个itemsControl

<ItemsControl ItemsSource="{Binding Path=Occupants}" IsEnabled="{Binding Path=AreOccupantsEditable}">
相关问题