简体   繁体   English

WPF组合框值

[英]WPF combobox value

I have three combo boxes on a xaml window : 我在xaml窗口上有三个组合框:

<Grid>
    <ComboBox Name="cbo1" Margin="40,37,328,250"  SelectionChanged="OnComboBoxChanged" />
    <ComboBox Name="cbo2" Margin="40,145,328,142" SelectionChanged="OnComboBoxChanged"/>
    <ComboBox Name="cbo3" Margin="40,91,328,196" SelectionChanged="OnComboBoxChanged" />
</Grid>

I assign the value to these on load , I am working on writing a routine that can loop through an array which has the names for these combo boxes and get the selected value : 我将这些值分配给加载时的值,我正在编写一个例程,该例程可以遍历具有这些组合框名称的数组并获取所选值:

string[] comboNameLst = {"cbo1","cbo2" , "cbo3" }; 
foreach (string s in comboNameLst)
{                
    ComboBox cbo = new ComboBox();
    cbo.Name = s;

    MessageBox.Show("ID is" + id + "and cbo is" + cbo.Name);
    MessageBox.Show("selected item" + cbo.SelectedItem  );
}

I am getting the value as null. 我将值设为null。 I need to be able to get selected values for these drop downs I know I could use the logical tree helper loop through all the objects and get the value but I dont want to be able to do it that way as I have too many controls and it will be very tricky. 我需要能够获得这些下拉菜单的选定值,我知道我可以使用逻辑树帮助程序遍历所有对象并获取值,但是我不想那样做,因为我有太多控件和这将非常棘手。

Instead of creating a new combo box in your loop, you need to actually use the boxes from your UI: 无需在循环中创建新的组合框,而是需要实际使用UI中的框:

ComboBox[] comboNameLst = {cbo1, cbo2, cbo3}; 
foreach (ComboBox cbo in comboNameLst)
{                
    MessageBox.Show("ID is" + id + "and cbo is" + cbo.Name);
    MessageBox.Show("selected item" + cbo.SelectedItem  );
}

I would also like to point out that you can avoid this type of code completely with binding. 我还想指出,您可以通过绑定完全避免这种类型的代码。 You can bind properties to the combo boxes using ItemsSource and bind a property to SelectedValue like so. 您可以使用ItemsSource将属性绑定到组合框,然后将属性绑定到SelectedValue。

<ComboBox ItemsSource="{Binding ListProperty}" 
            DisplayMemberPath="ValueString" 
            SelectedValuePath="ValueString" 
            SelectedValue="{Binding SelectedValueProperty}" />

This will provide the currently selected values directly to your bound properties for use in your code without the grunt work of adding items and getting their currently selected values via code-behind. 这将直接将当前选定的值提供给绑定属性,以供您在代码中使用,而无需费力地添加项目并通过后台代码获取其当前选定的值。

Here is an article for more detail. 是更详细的文章。

I hope this helps. 我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM