当用户在WPF中更改组合框时,SelectionChanged不会触发

时间:2015-01-31 02:33:09

标签: c# wpf events

因此我的selectionChanged事件在用户更改时不会触发,但如果我在代码中更改它则会触发。

我使用selectionchanged从组合框中选择一个来填充另一个组合框。



<!--1st list -->
<ComboBox ItemsSource="{Binding djurKatList}" SelectedItem="{Binding SelectedDjurKat}" SelectionChanged="listKat_SelectionChanged" x:Name="listKat" HorizontalAlignment="Left" Margin="98,118,0,0" VerticalAlignment="Top" Width="120"/>

<!--2nd list that's filled after something is selected in 1st list-->
<ComboBox ItemsSource="{Binding djurArtList}" SelectedItem="{Binding SelectedDjurArt}" x:Name="listDjur" HorizontalAlignment="Left" Margin="98,154,0,0" VerticalAlignment="Top" Width="120"/>
&#13;
&#13;
&#13;

在后面的代码中填充第二个组合框并且在我更改第一个组合框时没有执行:

private void listKat_SelectionChanged(object sender, SelectionChangedEventArgs e)
{            
    fyllDjurArtLista(hanterare, typeof(Daggdjur));
}

当我更改代码中的选择时,selectionChanged会触发,下面我更改了我选择的comboboxitem,事件被触发,第二个组合框被填满。

var listItem = new ComboBoxItem { Content = "Välj kategori" };
SelectedDjurKat = listItem;

1 个答案:

答案 0 :(得分:0)

这是一个简单的例子,它有效。

/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();

        VM v = new VM();
        v.djurKatList = new List<string>();
        v.djurKatList.Add("1");
        v.djurKatList.Add("2");
        v.djurKatList.Add("3");
        v.djurKatList.Add("4");
        v.djurKatList.Add("5");

        DataContext = v;
    }

    private void listKat_SelectionChanged(object sender, SelectionChangedEventArgs e) {
       // fyllDjurArtLista(hanterare, typeof(Daggdjur));
    }
}

public class VM {
    public List<string> djurKatList { get; set; }
    public string SelectedDjurKat { get; set; }
}

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <StackPanel>
        <!--1st list -->
        <ComboBox ItemsSource="{Binding djurKatList}" SelectedItem="{Binding SelectedDjurKat}" SelectionChanged="listKat_SelectionChanged"
                  x:Name="listKat" HorizontalAlignment="Left" Margin="98,118,0,0" VerticalAlignment="Top" Width="120"/>

        <!--2nd list that's filled after something is selected in 1st list-->
        <ComboBox ItemsSource="{Binding djurArtList}" SelectedItem="{Binding SelectedDjurArt}" x:Name="listDjur" HorizontalAlignment="Left"
                  Margin="98,154,0,0" VerticalAlignment="Top" Width="120"/>
    </StackPanel>
</Grid>

LaserChanged被触发。但如果问题是其他组合框未填充,则需要按照建议使用INotifyPropertyChanged。您需要为属性djurArtList调用PropertyChanged。