簡體   English   中英

從組合框中獲取選定值 C# WPF

[英]Get selected value from combo box in C# WPF

我剛剛開始使用 WPF forms 而不是 Windows Forms forms。在 Windows Forms 表格中我可以這樣做:

ComboBox.SelectedValue.toString();

這會很好用。

我如何在 WPF 中執行此操作? 它似乎沒有選項。

好吧..我找到了一個更簡單的解決方案。

String s = comboBox1.Text;

這樣,我將選定的值作為字符串。

與舊的WF表單相比,我發現這樣做有點奇怪:

ComboBoxItem typeItem = (ComboBoxItem)cboType.SelectedItem;
string value = typeItem.Content.ToString();

確保已在XAML文件中設置了ComboBox的名稱:

<ComboBox Height="23" Name="comboBox" />

在代碼中,您可以使用SelectedItem屬性訪問所選項目:

MessageBox.Show(comboBox.SelectedItem.ToString());

我的XAML如下所示:

<ComboBox Grid.Row="2" Grid.Column="1" Height="25" Width="200" SelectedIndex="0" Name="cmbDeviceDefinitionId">
    <ComboBoxItem Content="United States" Name="US"></ComboBoxItem>
    <ComboBoxItem Content="European Union" Name="EU"></ComboBoxItem>
    <ComboBoxItem Content="Asia Pacific" Name="AP"></ComboBoxItem>
</ComboBox>

內容顯示為文本和WPF組合框的名稱。 為了獲得所選項目的名稱,我遵循以下代碼行:

ComboBoxItem ComboItem = (ComboBoxItem)cmbDeviceDefinitionId.SelectedItem;
string name = ComboItem.Name;

要獲取WPF組合框的選定文本,請執行以下操作:

string name = cmbDeviceDefinitionId.SelectionBoxItem.ToString();

這些怎么樣:

string yourstringname = (yourComboBox.SelectedItem as ComboBoxItem).Content.ToString();

這取決於您綁定到ComboBox的對象。 如果您綁定了一個名為MyObject的對象,並且擁有一個名為Name的屬性,請執行以下操作:

MyObject mo = myListBox.SelectedItem as MyObject;
return mo.Name;

解決這個問題很簡單。 我所做的就是將“ SelectedValuePath”添加到我的XAML代碼中,並將其綁定到我想隨組合框返回的模型屬性。

<ComboBox SelectedValuePath="_Department"
          DisplayMemberPath="_Department"
          Height="23"
          HorizontalAlignment="Left"
          ItemsSource="{Binding}"
          Margin="-58,1,0,5"
          Name="_DepartmentComboBox"
          VerticalAlignment="Center"
          Width="268"/>

作為ComboBox SelectionChanged事件處理程序中的一個變體:

private void ComboBoxName_SelectionChanged(object send ...
{
    string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}

創建一個ComboBox SelectionChanged事件,並在WPF設計中設置ItemsSource =“ {Binding}”:

碼:

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string ob = ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString();
    MessageBox.Show(ob);
}

這在很大程度上取決於盒子的填充方式。 如果通過將DataTable (或其他集合)附加到ItemsSource ,則可能會發現將SelectionChanged事件處理程序附加到XAML中的框,然后在有用的代碼后面使用它:

private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    string s = ((DataRowView)cbx.Items.GetItemAt(cbx.SelectedIndex)).Row.ItemArray[0].ToString();
}

我在這里看到了另外兩個答案,其中有不同的部分-一個答案是ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString(); ,看起來很相似,但沒有將盒子投射到DataRowView ,我發現我需要做的事情,以及另一個: ((DataRowView)comboBox1.SelectedItem).Row.ItemArray[0].ToString(); ,使用.SelectedItem代替.Items.GetItemAt(comboBox1.SelectedIndex) 那可能.SelectedItem ,但是我確定的實際上是我上面寫的兩者的組合,並且不記得為什么我避免使用.SelectedItem只是在這種情況下它不一定適合我。

如果要動態填充框,或者直接在XAML中的下拉列表中使用ComboBoxItem項,則這是我使用的代碼:

private void ComboBoxName_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cbx = (ComboBox)sender;
    string val = String.Empty;
    if (cbx.SelectedValue == null)
        val = cbx.SelectionBoxItem.ToString();
    else
        val = cboParser(cbx.SelectedValue.ToString());
}

您會在那里看到cboParser 這是因為SelectedValue的輸出如下所示: System.Windows.Controls.Control: Some Value 至少在我的項目中。 因此,您必須從中解析出Some Value

private static string cboParser(string controlString)
{
    if (controlString.Contains(':'))
    {
        controlString = controlString.Split(':')[1].TrimStart(' ');
    }
    return controlString;
}

但這就是為什么此頁面上有這么多答案的原因。 這很大程度上取決於您如何裝箱,以及如何從中獲取價值。 答案在一種情況下可能是正確的,而在另一種情況下可能是錯誤的。

我有一個類似的問題,並嘗試了該線程中提出的許多解決方案,但發現在ComboBox項實際更新以顯示新選擇之前觸發了SelectionChanged事件(即,它始終在更改前給出組合框的內容發生)。

為了克服這個問題,我發現最好使用自動傳遞給事件處理程序的e參數,而不是嘗試直接從組合框中加載值。

XAML:

<Window.Resources>
    <x:Array x:Key="Combo" Type="sys:String">
        <sys:String>Item 1</sys:String>
        <sys:String>Item 2</sys:String>
    </x:Array>
</Window.Resources>
<Grid>
    <ComboBox Name="myCombo" ItemsSource="{StaticResource Combo}" SelectionChanged="ComboBox_SelectionChanged" />
    <TextBlock Name="MyTextBlock"></TextBlock>
</Grid>

C#:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string chosenValue = e.AddedItems[0].ToString();
}
private void usuarioBox_TextChanged(object sender, EventArgs e)
{
    string textComboBox = usuarioBox.Text;
}
MsgBox(cmbCut.SelectedValue().ToString())

要獲取C#中ComboBox選定索引的值,請使用:

Combobox.SelectedValue

實際上,您也可以按照以下方式進行操作。

假設您的ComboBox名稱為comboBoxA 然后其值可以得到為:

string combo = comboBoxA.SelectedValue.ToString();

我想現在已經支持了,因為您的問題已有五年歷史了。

這是相同的原則。

您可以使用SelectedIndex並使用ComboBox.Items [SelectedIndex] .ToString()。 或者只是ComboBox.SelectedItem並將其轉換為您需要的任何類型:)

像這樣寫:

String CmbTitle = (cmb.SelectedItem as ComboBoxItem).Content.ToString()

如果您想獲得價值並驗證它,可以執行以下操作

string index = ComboBoxDB.Text;
        if (index.Equals(""))
        {                
            MessageBox.Show("your message");
        }
        else
        {
            openFileDialog1.ShowDialog();
            string file = openFileDialog1.FileName;
            reader = new StreamReader(File.OpenRead(file));
        }
        // -----------------------------------------------------------------

        private void onSelectionChanged(object sender, 
                                        SelectionChangedEventArgs e)
        {
            String result = ((ComboBox)sender).SelectedItem.ToString();
            // do something with result
        }

        // -----------------------------------------------------------------

我發現這很有用。 我把它留在這里以防萬一有人需要它:

要獲取值:

(comboBox1.SelectedItem as dynamic).Value

要獲取文本:

(comboBox1.SelectedItem as dynamic).Text
<ComboBox x:Name="TestComboBox" SelectionChanged="TestComboBox_SelectionChanged" Padding="2">
    <ComboBoxItem>Item 1</ComboBoxItem>
    <ComboBoxItem>Item 2</ComboBoxItem>
</ComboBox>

方法一

string content = (((sender as ComboBox).SelectedValue) as ComboBoxItem).Content.ToString();

方法二

string content = (string)((ComboBoxItem)((ComboBox)sender).SelectedValue).Content;

一個對我有用的簡單解決方案是:

string name = (string)combobox.SelectedItem

您可以通過屬性SelectedValue提取值。 像這樣:

combo.SelectedValue.ToString();

我使用此代碼,它對我有用:

DataRowView typeItem = (DataRowView)myComboBox.SelectedItem; 
string value = typeItem.Row[0].ToString();

XAML:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="19,123,0,0" Name="comboBox1" VerticalAlignment="Top" Width="33" ItemsSource="{Binding}" AllowDrop="True" AlternationCount="1">
    <ComboBoxItem Content="1" Name="ComboBoxItem1" />
    <ComboBoxItem Content="2" Name="ComboBoxItem2" />
    <ComboBoxItem Content="3" Name="ComboBoxItem3" />
</ComboBox>

C#:

if (ComboBoxItem1.IsSelected)
{
    // Your code
}
else if (ComboBoxItem2.IsSelected)
{
    // Your code
}
else if(ComboBoxItem3.IsSelected)
{
    // Your code
}

這個對我有用:

System.Data.DataRowView typeItem = (System.Data.DataRowView)ComboBoxName.SelectedItem;
string value = typeItem.DataView.ToTable("a").Rows[0][0].ToString();

暫無
暫無

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

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