【问题标题】:Store Combobox items in The Form of Array and Retrieve SelectedId in WPF以数组的形式存储 Combobox 项并在 WPF 中检索 SelectedId
【发布时间】:2012-10-08 17:04:37
【问题描述】:

我是一名 C++ 开发人员,最近转到了这个令人惊叹的 WPF 世界。我正在开发一个 WPF 应用程序。我的 xaml 文件中有一个组合框 (BusRate)。

<ComboBox Height="23" ItemsSource="{Binding BusRateList}" SelectedIndex="2" Name="comboBox2" Width="85" />

我的 Viewmodel 类具有以下属性:

public ObservableCollection<int> _busRate = new ObservableCollection<int>();
public ObservableCollection<int> BusRateList
    {
        get { return _busRate; }
        set
        {
            _busRate = value;
            NotifyPropertyChanged("BusRateList");
        }
    }

我添加的项目如下:

_busRate.Add(10);
_busRate.Add(50);
_busRate.Add(100);
_busRate.Add(200);
_busRate.Add(300);
_busRate.Add(400);
_busRate.Add(500);
_busRate.Add(600);      

这给了我组合框中的项目。但是我想以包含所有这些值的数组的形式将这些项目添加到我的组合框中。例如:

// C++ Code
static const char *busRate[8] = 
{
" 10", " 50", "100", "200", "300", "400", "500", "600"
};

因此允许我对comboboxitemselected 方法执行以下操作:

  • 从 Combobox 中获取 SelectedId 并将其存储在一个整数变量中。
  • 传递这个整数变量。演示如下:

    int id = comboBox->getSelectedId(); // C++ Code
    unsigned long speed = String(busRate[id-1]).getIntValue(); // C++ Code
    

如何在我的应用程序中实现这一点:)

【问题讨论】:

    标签: c# c++ wpf combobox


    【解决方案1】:

    您可以在您的 ViewModel 中创建一个 int 类型的新属性和一个 converter,它将字符串转换为 int 值。现在将新属性绑定到 ComboBox.SelectedItem-property:

    <Window/UserControl/....Resouces>
        <local:YourConverter x:Key="TheConverter"/>
    <Window/UserControl/....Resouces>
    
    <ComboBox SelectedIten="{Binding Path=IntProp, Converter={StaticResource TheConverter}}"
    

    编辑:

    int id = Convert.ToInt32(BusRateList[comboBox.SelectedIndex]);
    

    【讨论】:

    • 感谢您的回复。但是难道不能用简单的数组方法来执行操作吗???如果你注意到最后的两点,c++ 中的这些行在我的课程中扮演着重要的角色。我只是想让事情变得简单。他们是这样做的吗?
    • 哇,太棒了:) 这清除了我的第一个障碍。第二个呢???我如何获得 busrate[id-1] 和 IntValue 并将其存储在 unsignedLong 中,如我的第二点所述:) 由于我没有使用 Array,现在我可以使用 busrate[id-1] 吗? ??
    • 有可能,但不是必须的。您可以将所选项目绑定到视图模型中的属性并将其转换为字符串。替代方案: var index = _busRate.IndexOf(_selectedItem); var value = _busRate[index].ToString();
    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 2016-12-26
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多