我有一个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; }
}
我也为我的ListView设置了DataContext
:
lvRSU.DataContext = this;
但我根本无法获得组合框中的物品。也许有问题,因为它在网格内?
我现在好了。
ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView},Path=DataContext.sensorTypes}"
这个与众不同。我要去ListView的DataContext,它在某些时候包含我的组合框,我从那里设置Path。感谢。
答案 0 :(得分:0)
我在代码中找不到任何错误。 所以我的建议是你可以使用这个方法来调试数据绑定:Debug DataBinding using IValueConverter
希望您能找到错误并告诉所有人。祝你好运!
答案 1 :(得分:0)
我认为可能是:
lvRSU.DataContext = this.sensorTypes;
或者最好将它绑定在XAML中,正如您所注意到的那样:
ItemsSource="{Binding sensorTypes, RelativeSource={RelativeSource AncestorType=ListView}}"