2011-06-20 76 views
0

在WPF的列表框我開始用WPF一個文本框和我有這個很簡單的問題:如何同步使用IsSynchronizedWithCurrentItem

我有一個TextBlock和一個列表框共享相同的DataContext。 ListBox的ItemsSource被設置爲指向其ObservableCollection的DataContext屬性。我希望TextBlock包含Listbox的選定項目。有些代碼:

View view = new View(); 
view.DataContext = new ViewModel(); 
view.Show(); 
<TextBlock Name="textBox1" Grid.Row="0" Grid.Column="0" Margin="1" Text="{Binding ¿xxx?}"></TextBlock> 
<ListBox Name="listBox1" Grid.Row="1" Grid.ColumnSpan="2" Margin="1" ItemsSource="{Binding Model.BinariesToDeploy}" IsSynchronizedWithCurrentItem="True" /> 

希望其明確的。

回答

1

嘗試這樣的事情

Text = "{Binding ElementName=listBox1, Path=SelectedValue.Content}" 
+0

這樣的作品,謝謝。我如何學習綁定的語法和可用的屬性?什麼是綁定?一類?再次感謝。 –

+1

是的,'綁定'是'System.Windows.Data'中的一個類。關於可用的屬性,您可以使用智能感知來找出可用的屬性。關於如何學習語法,你可以谷歌找出樣本,你可以通過它學習。 –

+2

看到這個http://www.nbdtech.com/Free/WpfBinding.pdf這是基於XAML的數據綁定備忘錄 –

2

如果你確實想用你需要綁定到集合的當前項目將由具有IsSynchronizedWithCurrentItem集到列表框或任何其它控制設置的同步true,這麼做使用/

<TextBlock Text="{Binding Model.BinariesToDeploy/}" /> 

當源是一個集合視圖,當前項可以與規定斜線(/)。例如,子句Path = /設置綁定到視圖中的當前項目。當源是集合時,此語法指定默認集合視圖的當前項目。

當前項目由CollectionView管理,它是原始集合上的圖層,CollectionViews也可用於過濾,排序和分組。


一個例子(可以在Kaxaml查看):

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
    <Page.Resources> 
     <x:Array x:Key="items" Type="{x:Type Label}"> 
      <Label Content="Apple" Tag="Fruit"/> 
      <Label Content="Pear" Tag="Fruit"/> 
      <Label Content="Orange" Tag="Fruit"/> 
      <Label Content="Lime" Tag="Fruit"/> 
      <Label Content="Tomato" Tag="Vegetable"/> 
      <Label Content="Radish" Tag="Vegetable"/> 
      <Label Content="Lettuce" Tag="Vegetable"/> 
     </x:Array> 
    </Page.Resources> 
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> 
     <StackPanel> 
      <ListBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource items}}"/> 
      <!-- Binds to CurrentItem.Content --> 
      <ContentControl Content="{Binding /Content,Source={StaticResource items}}"/> 
     </StackPanel> 
    </ScrollViewer> 
</Page> 
+0

你好,這段代碼有一個警告:它說預計財產。這真的很重要嗎? –

+0

嗯,我不知道你的集合包含什麼樣的項目,這個綁定直接綁定到選定的項目,所以你可能想在斜槓後面指定一個屬性。理論上說,綁定應該是正確的。 –