2016-01-05 174 views
0

在我的例子中我綁定到一個ListBox的selectedItem。我想知道如何設置堆棧面板中的綁定,所以我不必然後單獨綁定到每個控件。wpf綁定到selectedItem

我可以只綁定堆棧面板,然後將子控件只得到約束,像這樣(僞代碼)

<StackPanel Grid.Column="2" Content="{Binding SelectedItem.Name, ElementName=ItemList}"/> 
    <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"/> 
    <TextBox Text="{Binding Kids, UpdateSourceTrigger=PropertyChanged}"/> 
    <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/> 
</StackPanel> 

代碼

<ListBox Grid.Column="0" 
       x:Name="ItemList" 
       Background="AliceBlue" 
       ItemsSource="{Binding VNodes}" 
       SelectedItem="{Binding SelectedVNode, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"> 
      <ListBox.ItemTemplate> 
       <DataTemplate> 
        <WrapPanel> 
         <TextBlock Text="Name: " /> 
         <TextBlock Text="{Binding Name}" FontWeight="Bold" /> 
        </WrapPanel> 
       </DataTemplate> 
      </ListBox.ItemTemplate> 
     </ListBox> 

     <GridSplitter Grid.Column="1" Width="5" HorizontalAlignment="Stretch" /> 

     <StackPanel Grid.Column="2"> 
      <TextBox Text="{Binding SelectedItem.Name, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/> 
      <TextBox Text="{Binding SelectedItem.Kids, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/> 
      <TextBox Text="{Binding SelectedItem.Age, ElementName=ItemList, UpdateSourceTrigger=PropertyChanged}"/> 
     </StackPanel> 

回答

2

在WPF中,每個項目有DataContext for Bindings,您可以將StackPanel的DataContext設置爲 {Binding ElementName=ItemList, Path=SelectedItem}

,簡單地把 <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}"/>

的StackPanel的內側,你想;)

相關問題