【问题标题】:WinRT ComboBox SelectedValue is nullWinRT ComboBox SelectedValue 为空
【发布时间】:2016-04-04 08:21:40
【问题描述】:

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

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的状态

【问题讨论】:

  • 您是否尝试设置SelectedIndexSelectedValue 属于 object 类型,您需要将其指定为集合中的对象之一才能使其工作。
  • 你选择的索引正在设置,但这不是我想要的
  • 我试过 cbstate.SelectedValue = mystateobject 但它仍然为空
  • 试试&lt;ComboBox ... SelectedValuePath="Value" /&gt;
  • 你是说cbstate.SelectedValue = state_items[3] 不起作用?

标签: xaml windows-phone-8 windows-runtime win-universal-app uwp-xaml


【解决方案1】:

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

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

代码如下

states = Location.GetStates();

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

第二种方法如 cmets 部分所建议的那样

 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>

此外,我想向我的 WinRT 开发人员同事发布消息,不需要像我在问题中那样创建一个单独的类,如 ComboBoxItemClass 来使用组合框。只需获取您的状态列表,将其分配给 ItemSource 并使用上述任何方法。

此外,如果您想要 ComboBox 中的 State_Name 和 State_Id,您也可以这样做。

State mystate=(State)ComboBox.SelectedItem;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 2021-07-07
    相关资源
    最近更新 更多