0

我是 WPF 的新手,我想根据 ComboBox 值从代码中隐藏/显示一些控件,如 TextBlock、ComboBox 等。我已经搜索了一些没有运气的解决方案。我经常关注答案。

textbox1.Visibility = Visibility.Hidden;

所以,我尝试了这个。

    private void cbBuscar_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        MessageBox.Show(cbBuscar.SelectedIndex.ToString());

        if (cbBuscar.SelectedIndex == 0)
        {
           cbProduto.Visibility = Visibility.Hidden;
        }
        else if (cbBuscar.SelectedIndex == 1)
        {
            cbProduto.Visibility = Visibility.Visible;
        }
        else if (cbBuscar.SelectedIndex == 2)
        {
            cbProduto.Visibility = Visibility.Collapsed;
        }
    }

简单是行不通的。尝试我收到此错误{“对象引用未设置为对象的实例。”}

做我想做的事一定不难,实际上一定很容易。那么,谁能告诉我做错了什么?

4

1 回答 1

1

Try placing the following code inside your cbBuscar_SelectionChanged function:

if (!IsLoaded)
    return;

If the selection is changing before the window initializes, this may fix the problem.

So your function would look like this:

private void cbBuscar_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (!IsLoaded)
        return;

    MessageBox.Show(cbBuscar.SelectedIndex.ToString());

    if (cbBuscar.SelectedIndex == 0)
    {
       cbProduto.Visibility = Visibility.Hidden;
    }
    else if (cbBuscar.SelectedIndex == 1)
    {
        cbProduto.Visibility = Visibility.Visible;
    }
    else if (cbBuscar.SelectedIndex == 2)
    {
        cbProduto.Visibility = Visibility.Collapsed;
    }
}
于 2013-07-28T23:07:26.307 回答