0

我创建了一个类来创建要添加到组合框的项目

public class ComboBoxItemClass
{
    public string Text { get; set; }
    public object Value { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

对于组合框,我的 XAML 如下

<TextBlock Text="State"/>
<ComboBox x:Name="cbState"/>

我在代码隐藏中的 C# 代码如下

private void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
    {
        List<ComboBoxItemClass> state_items = new List<ComboBoxItemClass>();

        List<State> states = Location.GetStates();
        foreach(State s in states)
        {
            ComboBoxItemClass item = new ComboBoxItemClass() { Text = s.State_Name, Value = s.State_Id };
            state_items.Add(item);
        }
        cbState.ItemsSource = state_items;
        cbState.SelectedValue = 3;

在模拟器中运行的组合框不显示选中状态。单击它会显示状态列表。

在调试 selectedvalue 时,尽管为其分配了值,但仍显示为 null。其余代码没有问题,存在 State_Id=3 的状态

4

1 回答 1

0

我已经通过两种方式解决了这个问题

第一种方法是获取 states 变量中的状态列表。将此分配给 ComboBox ItemSource。然后获取 State_Id 并从相同的状态列表中找到该特定状态的索引并将其分配给选定的索引。

后面的代码如下

states = Location.GetStates();

cbState.ItemsSource = states;
cbState.SelectedIndex = states.IndexOf(states.Where(x=>x.State_Id==State_Id).First());

第二种方法如评论部分所建议

 states = Location.GetStates();
 cbState.ItemsSource = states;
 int index=states.IndexOf(states.Where(x=>x.State_Id==State_Id).First());
 cbState.SelectedItem = states[index];

XAML如下

<ComboBox x:Name="cbState" >
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding State_Name}"></TextBlock>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

Also I would like to post to my fellow WinRT developers that it is not required to create a separate class like ComboBoxItemClass like I did in the question to use combo box. Just get the list of your states, assign it to ItemSource and use any of the above methods.

Also if you want the State_Name and State_Id from the ComboBox you can do this.

State mystate=(State)ComboBox.SelectedItem;
于 2016-04-04T15:18:47.260 回答