2009-12-16 135 views
10

在我的viewmodel我有int屬性,我想暴露它的編輯與組合框,有限的選擇,如16,8,4和2.有沒有一種方法來指定選擇XAML,同時仍將值綁定回視圖模型?我願意做這樣的事情:數據綁定WPF組合框與在XAML中定義的選擇?

<ComboBox SelectedValue="{Binding MyIntProperty}"> 
    <ComboBoxItem>16</ComboBoxItem> 
    <ComboBoxItem>8</ComboBoxItem> 
    <ComboBoxItem>4</ComboBoxItem> 
    <ComboBoxItem>2</ComboBoxItem> 
</ComboBox> 

我知道我可以搭起代碼中List<int>,並設置爲ItemsSource時,但我希望有一種方法可以做到這一點不涉及視圖模型中的一個額外屬性,用於顯示在代碼中創建的集合。

回答

13

您可以完全按照您的示例指定您的選擇。它看起來像缺少,使其工作,是SelectedValuePath屬性。沒有它,SelectedValue將與SelectedItem相同。通過在ComboBox中設置SelectedValuePath =「Content」,可以指定將SelectedValue綁定僅綁定到SelectedItem的一部分,在這種情況下,將指定爲每個ComboBoxItem中內容的Int內容。

下面是一個小演示,並將其綁定到TextBox,您可以在其中設置項並通過SelectedValue綁定在ComboBox中看到它(反之亦然)。

<StackPanel> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Set Value:" /> 
     <TextBox Text="{Binding MyIntProperty, UpdateSourceTrigger=PropertyChanged}" /> 
    </StackPanel> 
    <StackPanel Orientation="Horizontal"> 
     <TextBlock Text="Select Value:" /> 
     <ComboBox SelectedValue="{Binding MyIntProperty}" SelectedValuePath="Content"> 
      <ComboBoxItem>2</ComboBoxItem> 
      <ComboBoxItem>4</ComboBoxItem> 
      <ComboBoxItem>6</ComboBoxItem> 
      <ComboBoxItem>8</ComboBoxItem> 
      <ComboBoxItem>16</ComboBoxItem> 
     </ComboBox> 
    </StackPanel> 
</StackPanel> 
+0

啊啊謝謝。我實際上已經嘗試過那件事,但認爲它沒有工作,因爲我的財產還沒有設置。仍然,很高興有明確的答案,因爲我在搜索時找不到它。 – RandomEngy 2009-12-16 22:48:48