【问题标题】:Combo Box 1st item is remained empty in WPF c#组合框第一项在 WPF c# 中保持为空
【发布时间】:2015-08-24 06:42:06
【问题描述】:

我的 wpf 中有一个组合框和两个名为:

  1. 发送
  2. 接收。

我想让组合框在首次加载 WPF 时显示一般消息(发送/接收)。 我尝试将字符串应用于 XAML 中的 Text 属性,但没有成功:

<ComboBox x:Name="opBox" HorizontalAlignment="Left" Text="Send/Receive"/> 

有什么方法可以应用此文本使其不作为一个项目?

In addition, when one of the items is selected I'm hiding or making visible the appropriate button by an event called SelectionChanged.但是,如果用户再次选择一般消息发送/接收,我希望 2 个按钮隐藏在一起。当我尝试在 SelectionChanged 中执行此操作时,出现了一些错误。

更新: 这是我的 SelectionChanged 事件:

private void opBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        if (opBox.SelectedIndex == 1)//Send
        {

            mySendButton.Visibility = Visibility.Visible;
            myReceiveButton.Visibility = Visibility.Hidden;
        }
        else if(opBox.SelectedIndex==2)//Receive
        {

            mySendButton.Visibility = Visibility.Hidden;
            myReceiveButton.Visibility = Visibility.Visible;
            ClearTextBox();
        }
        else if (opBox.SelectedIndex == 0)//Send or Receive
        {

                mySendButton.Visibility = Visibility.Hidden;
                myReceiveButton.Visibility = Visibility.Hidden;

        } 

【问题讨论】:

    标签: c# combobox wpf-controls


    【解决方案1】:

    尝试设置IsEditableIsReadonly 属性,如下所示:

    <ComboBox x:Name="opBox" IsEditable="True" IsReadOnly="True" HorizontalAlignment="Left" Text="Send/Receive"/>
    

    要阻止您的代码在InitializeComponent() 上崩溃,请在opBox_SelectionChanged 之上添加以下代码

    if (mySendButton==null||myReceiveButton==null)
        return;
    

    另请注意,直接从事件处理程序管理控件属性不是 WPF 方式。最好使用数据绑定和基于视图模型的方法来自定义 WPF UI 行为。

    【讨论】:

    • 您好,我更新了我的代码并尝试使用您编写的内容,但它仍然会产生类似的错误:MyMahappsExtended.exe 中发生“System.NullReferenceException”类型的异常,但未在用户中处理代码附加信息:对象引用未设置为对象的实例。
    • 我调试了它,当程序在 InitializeComponent() 之后加载时;在主窗口中,它会自动转到 SelectionChanged 事件,并在那里说我的按钮为空;
    猜你喜欢
    • 2013-12-27
    • 2022-01-14
    • 1970-01-01
    • 2021-10-15
    • 2016-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-18
    相关资源
    最近更新 更多