ListBox上的MouseRightClick使应用程序崩溃

时间:2015-05-31 16:30:04

标签: c# wpf listbox

当我右键单击我的空列表框时,整个应用程序崩溃了,我甚至不知道如何调试它,放置try-catch等等。

有人遇到过这样的问题吗?关于如何解决这个问题的任何想法?

这是列表框中的我的XAML:

    <ListBox x:Name="LstStat" HorizontalAlignment="Left" Height="129" Margin="10,10,0,0" 
             VerticalAlignment="Top" Width="330" FontSize="16"
             ItemsSource="{Binding StatisticsQueries}" Cursor="Arrow">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Content="{Binding Path=Name}" FontWeight="Medium" FontSize="18" FontFamily="HelveticaNeueCyr"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

也许XAML在某种程度上是错误的?

更新

这是来自.cs的绑定

public ObservableCollection<Query> StatisticsQueries { get; private set; }
private void FillStatisticsList()
{
    const string statsQuery = "SELECT * FROM cached_queries WHERE is_statistics IS TRUE;";
    var connection = new MySqlConnection(DatabaseModel.ConnectionString);
    connection.Open();

    var cmd = new MySqlCommand(statsQuery, connection);

    cmd.ExecuteNonQuery();
    var reader = cmd.ExecuteReader();
    cmd.CommandType = CommandType.Text;

    StatisticsQueries = new ObservableCollection<Query>();

    while (reader.Read())
    {
        StatisticsQueries.Add(new Query
        {
            Id = reader["id"].ToString(),
            Autoschool = reader["autoschool"].ToString(),
            IsStatistics = reader["is_statistics"].ToString(),
            Name = reader["query_name"].ToString(),
            Text = reader["query_text"].ToString()
        });
    }
    connection.Close();
}

以下是我在Window_Loaded事件中所做的事情:

await Task.Run(() => FillStatisticsList());

这是与我的ListBox连接的所有代码,但它与RightMouseClick无关...为什么它不会在任何其他点击或其他东西上崩溃?

2 个答案:

答案 0 :(得分:2)

尝试执行以下操作:包含try-catch块并显示错误消息:

private void FillStatisticsList()
{
    try
    {
        const string statsQuery = "SELECT * FROM cached_queries WHERE is_statistics IS TRUE;";
        var connection = new MySqlConnection(DatabaseModel.ConnectionString);
        connection.Open();

        var cmd = new MySqlCommand(statsQuery, connection);

        cmd.ExecuteNonQuery();
        var reader = cmd.ExecuteReader();
        cmd.CommandType = CommandType.Text;

        StatisticsQueries = new ObservableCollection<Query>();

        while (reader.Read())
        {
            StatisticsQueries.Add(new Query
            {
                Id = reader["id"].ToString(),
                Autoschool = reader["autoschool"].ToString(),
                IsStatistics = reader["is_statistics"].ToString(),
                Name = reader["query_name"].ToString(),
                Text = reader["query_text"].ToString()
            });
        }
        connection.Close();
    }
    catch (Exception ex) { MessageBox.Show(ex.Message); }
}

希望这可能会有所帮助。

答案 1 :(得分:1)

感谢大家! 通过禁用我的ListBox上的鼠标右键来解决它。

Minitest.should_shuffle_suites = false