我有一个ListView
这样的声明:
<ListView x:Name="lvRSU" Margin="3" Background="#84978F" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ItemsSource="{Binding rsus}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Grid.Row="0" VerticalAlignment="Center">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="240"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="40"/>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Content="{Binding Name}" ContentStringFormat="{}{0} Path" VerticalAlignment="Center" />
<TextBox Grid.Column="1" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="2,0,0,0"/>
<Button Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="22" Height="22" MaxHeight="22" MaxWidth="22" ToolTip="Open .rsu file" SnapsToDevicePixels="True">
<Image Source="Resources/Folder16.png" Stretch="Uniform" ></Image>
</Button>
<CheckBox Grid.Column="3" Content="En" VerticalAlignment="Center"/>
<ComboBox ItemsSource="{Binding sensorTypes}" Grid.Column="4" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"/>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<CheckBox Grid.Column="5" Content="{Binding Name}" ContentStringFormat="Inv {0}" VerticalAlignment="Center" Margin="2,1,1,1"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
在 .cs 文件中,我有以下连接:
public ReadOnlyObservableCollection<string> _sensorTypes =
new ReadOnlyObservableCollection<string>(new ObservableCollection<string>() { "1", "2"});
public ReadOnlyObservableCollection<string> sensorTypes
{
get { return _sensorTypes; }
}
我也DataContext
为我的 ListView 设置:
lvRSU.DataContext = this;
但我根本无法获得组合框中的项目。也许有问题,因为它在网格内?
没关系,我现在明白了。
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView},Path=DataContext.sensorTypes}"
这一个有所作为。我要去 ListView 的 DataContext ,它在某个时候包含我的组合框,然后我从那里设置路径。谢谢。