循环浏览listview以获取Checkbox状态

时间:2016-01-18 13:56:21

标签: c# wpf

  <ListView Name="listViewLoadDisableSchems" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
        <ListView.View>
            <GridView>
                <GridViewColumn  >
                    <GridViewColumn.CellTemplate >
                        <DataTemplate >
                           <DataTemplate >
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center" >
                                <Label Name="lblSchemeID" VerticalAlignment="Center"  Margin="0" Content="{Binding Id}" Visibility="Hidden" />
                                <CheckBox Name="chkScheme" VerticalAlignment="Center" Margin="0,0,0,0" Content="{Binding Name}"  />
                            </StackPanel>
                        </DataTemplate>        
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

如果选中复选框,我想获取lblSchemeID。所以我可以更新数据库。 我如何才能点击?

1 个答案:

答案 0 :(得分:1)

您需要查看一些基本的MVVM模式才能实现这一目标。在XAML中试试这个:

<select name="select" id="select">
<?=$options ?>
</select>

和你在视图模型中的相同之处&amp;代码背后:

<select name="select" id="select">
  <option value="1000">Cost 10</option>
  <option value="2000">Cost 40</option>
  <option value="3000">Cost 80</option>
</select>
  
<Grid>
<Grid.RowDefinitions>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<ListView ItemsSource="{Binding Items}">
    <ListView.View>
        <GridView>
            <GridViewColumn>
                <GridViewColumn.CellTemplate >
                    <DataTemplate >
                        <StackPanel Orientation="Horizontal" HorizontalAlignment="Left" VerticalAlignment="Center" >
                            <CheckBox VerticalAlignment="Center" Margin="0,0,0,0" Content="{Binding Name}" IsChecked="{Binding IsSelected}"  />
                        </StackPanel>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>
<Button Grid.Row="1" Content="What is checked?" Command="{Binding GoCommand}"></Button>
   
public class MainViewModel
{
    public ObservableCollection<TestItem> Items { get; set; } = new ObservableCollection<TestItem> { new TestItem() { Id = 1, Name = "Foo" }, new TestItem() { Id = 2, Name = "Bar" } };

    public ICommand GoCommand => new DelegateCommand(Go);

    void Go()
    {
        MessageBox.Show(string.Join(Environment.NewLine, Items.Where(x => x.IsSelected).Select(x => x.Name)));
    }
}

您可以从Google获得委托命令的实现。如果您对此感到困难,请同样使用INotifyPropertyChanged。