父属性绑定

时间:2012-02-24 23:19:12

标签: .net wpf binding

拥有一个具有两个属性的ViewModel:Venue和States 场地是当前视图,通过表格(下方)选择并显示:

<StackPanel Orientation="Vertical" Margin="20,00,0,0" FlowDirection="LeftToRight" DataContext="{Binding Venue}">
            <TextBlock Text="Venue Name" Style="{StaticResource FormHeading}" />
            <TextBox x:Name="txtVenueName" Width="200" MaxLength="70" HorizontalAlignment="Left" Text="{Binding VenueName, Mode=TwoWay}" />

            <TextBlock Text="Address" Style="{StaticResource FormHeading}" />
            <TextBox x:Name="txtAddress" Width="300" MaxLength="100" HorizontalAlignment="Left" Text="{Binding Address, Mode=TwoWay}" />

            <TextBlock Text="City" Style="{StaticResource FormHeading}" />
            <TextBox x:Name="txtCity" Width="200" MaxLength="100" HorizontalAlignment="Left" Text="{Binding City, Mode=TwoWay}" />

            <TextBlock Text="State" Style="{StaticResource FormHeading}" />
            <ComboBox Width="70" HorizontalAlignment="Left" Name="cmbState" DisplayMemberPath="FullName"
                      ItemsSource="{Binding Path=States, ElementName=LayoutRoot}"/>

            <TextBlock Text="Zipcode" Style="{StaticResource FormHeading}" />
            <TextBox x:Name="txtZipCode" Width="50" MaxLength="5" HorizontalAlignment="Left" Text="{Binding Zipcode, Mode=TwoWay}" />

            <StackPanel Orientation="Horizontal" Margin="0,10,0,0">
                <TextBlock Text="Active?" Style="{StaticResource FormHeading}" Margin="0,0,10,0"  />
                <CheckBox Name="chkActive" />
            </StackPanel>
        </StackPanel>

然而,国家不是Venue的成员,但它是与Venue处于同一级别的财产。我该如何绑定此属性?看看RelativeSource,似乎并不是我想要的。

由于

1 个答案:

答案 0 :(得分:2)

目前您正在设置DataContext={Binding Venue}。一种选择是删除它,然后将其他绑定更改为Text="{Binding Venue.VenueName, ...}"等。然后您可以使用ItemsSource="{Binding Path=States, ..."}

或者,RelativeSource绑定可行。类似的东西:

ItemsSource="{Binding Path=States, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"

显然取决于StackPanel的父类型。