如何使用绑定获取组合框selectedItem值

时间:2012-11-23 05:05:52

标签: combobox silverlight-5.0 xaml-binding

我的组合框:

 <pmControls:pmComboBox Grid.Row="3" Grid.Column="1" Margin="3"  
  SelectedItem="{Binding Applicable_For,Mode=Two Way}" DisplayMemberPath="Applicable_For"
     SelectedValuePath="Applicable_For">

  <pmControls:pmComboBoxItem Content="Parcel" ></pmControls:pmComboBoxItem>
  <pmControls:pmComboBoxItem Content="Property"></pmControls:pmComboBoxItem>

  </pmControls:pmComboBox>

已将2个静态项添加到组合框作为宗地和属性,并希望获得这些值 使用绑定。

我已经绑定了SelectedItem,我的绑定字段是App​​licable_For。

使用上面的代码在Applicable_For中获取值为null。

编辑:我已经为我之前忘记的所选项目添加了Mode=Two Way

但它没有像'PropMgmt.Controls.pmComboBoxItem'那样获得名称空间

请帮助..

1 个答案:

答案 0 :(得分:2)

您可以为其创建集合,而不是将静态项添加到组合框。对于前创建类如:

public class KeyValuePair
{
    string key;

    public string Key
    {
        get { return key; }
        set { key = value; }
    }
    string value;

    public string Value
    {
        get { return this.value; }
        set { this.value = value; }
    }      

}

然后在您的视图模型中添加以下代码:

        ObservableCollection<KeyValuePair> applicable_For_KeyValues = new ObservableCollection<KeyValuePair>();

        KeyValuePair k1 = new KeyValuePair() { Key = "1", Value = "Parcel" };
        KeyValuePair k2 = new KeyValuePair() { Key = "2", Value = "Property" };

        applicable_For_KeyValues.Add(k1);
        applicable_For_KeyValues.Add(k2);

然后在xaml中添加以下内容:

<pmControls:pmComboBox Grid.Row="3" Grid.Column="1" Margin="3" 
 ItemsSource="{Binding Applicable_For_KeyValues}" 
 SelectedValue="{Binding Applicable_For,Mode=TwoWay}" SelectedValuePath="Value">
                <pmControls:pmComboBox.ItemTemplate >
                    <DataTemplate>
                        <TextBlock Text="{Binding Value}"></TextBlock>
                    </DataTemplate>
                </pmControls:pmComboBox.ItemTemplate>        

            </pmControls:pmComboBox>

希望这可以解决您的问题。