【问题标题】:Cannot do selectedIndexChanged in combobox c#(and xaml)无法在组合框 c#(和 xaml)中执行 selectedIndexChanged
【发布时间】:2018-11-22 03:07:01
【问题描述】:

我试图让用户从我的数据库中选择要显示的表,我听说这样做的最佳方法是使用“selectedIndexChanged”事件,这样当用户单击所需的表时,它会立即显示它。但是,由于某种原因,当我单击我的组合框,然后单击事件时,我没有看到“selectedIndexChanged”作为选项,并且在手动编写时说:“成员“SelectedIndexChanged”无法识别或无法访问” 这是我的 xaml 代码:

 <Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="4*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Canvas Name="mycanvas" Background="LightBlue" Margin="0,0,34.4,-0.2">
        <DataGrid Name="g1">
        </DataGrid>
        <Label Name="l1" Content="" FontWeight="ExtraBold" FontSize="15" Foreground="{x:Null}" Canvas.Left="20"/>
    </Canvas>
    <Canvas Grid.Column="1">
        <Label Name="Instruction" Content="Choose a table" FontWeight="ExtraBold" FontSize="15" Canvas.Left="-23" Canvas.Top="62"/>
        <ComboBox SelectedIndexChanged="b1" Name="ComboBox1" FontWeight="Bold" FontSize="15" Canvas.Top="98" Width="135" Height="24" Canvas.Left="-31">
            <ComboBoxItem Foreground="#FF3FA4C5"  Name="classesTbl">classesTbl</ComboBoxItem>
            <ComboBoxItem Foreground="#FF3FA4C5" Name="gradesTbl">gradesTbl</ComboBoxItem>
            <ComboBoxItem Foreground="#FF3FA4C5" Name="studentsTbl">studentsTbl</ComboBoxItem>
            <ComboBoxItem Foreground="#FF3FA4C5" Name="subjectsTbl">subjectsTbl</ComboBoxItem>
            <ComboBoxItem Foreground="#FF3FA4C5" Name="subjectsTeachers">subjectsTeachers</ComboBoxItem>
            <ComboBoxItem Foreground="#FF3FA4C5" Name="TeachersTbl">TeachersTbl</ComboBoxItem>
        </ComboBox>
    </Canvas>
</Grid>

有谁知道如何解决它或我做错了什么?

【问题讨论】:

    标签: c# wpf xaml selectedindexchanged


    【解决方案1】:

    SelectionChanged 属性可用于组合框,并可绑定命令。对应的action可以写在Viewmodel中针对命令

    【讨论】:

    • 是的,谢谢,我找到了,最后效果很好!
    【解决方案2】:

    WPF ComboBox 控件 (MSDN) 没有SelectedIndexChanged 事件,您可能会想到 WinForms 事件。

    除此之外;您应该使用 MVVM (MVVM: Tutorial from start to finish?) 并且不太依赖(如果有的话)控制事件。在这种情况下,您可以通过绑定 SelectedItem 并在视图模型属性的 setter 中更新 DataGrid 的 ItemsSource 绑定到的集合来轻松完成此操作。

    最后一点;使用Canvas 几乎可以肯定是不正确的;你应该坚持使用Grid,这样你就可以很好地调整大小而不是绝对定位。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多