簡體   English   中英

WPF C#中的組合框第一個項目保持空白

[英]Combo Box 1st item is remained empty in WPF c#

我的wpf中有一個combox和2個項目,分別是:

  1. 發送
  2. 接收。

我想使組合框在第一次加載WPF時顯示一般消息(發送/接收)。 我試圖將字符串應用於XAML中的Text屬性,但是它不起作用:

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

有什么方法可以應用此文本,因此不會作為項目使用?

另外,當選擇其中一項時,我會通過稱為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;

        } 

嘗試設置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行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM