列表视图项中的组合框绑定

本文关键字:组合 绑定 视图 列表 | 更新日期: 2023-09-27 18:37:02

我有一个像这样声明的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

lvRSU.DataContext = this;

但是我根本无法在我的组合框中获取这些项目。也许有问题,因为它在网格内?

没关系,我现在明白了。

 ItemsSource="{Binding RelativeSource={RelativeSource AncestorType=ListView},Path=DataContext.sensorTypes}"

这个与众不同。我将转到ListView的数据上下文,该上下文在某些时候包含我的组合框,并从那里设置路径。谢谢。

列表视图项中的组合框绑定

我在你的代码中找不到任何错误。所以我的建议是你可以使用这种方法来调试数据绑定:使用 IValueConverter 调试数据绑定

希望你能找到这个bug,告诉大家。祝你好运!

我认为可能是:

lvRSU.DataContext = this.sensorTypes;

或者最好在 XAML 中绑定它,如您所注意到的:

ItemsSource="{Binding sensorTypes, RelativeSource={RelativeSource AncestorType=ListView}}"