2012-06-25 103 views
1

我一直在試圖找到這個解決方案,但無法在網上找到相關答案。WPF基於combobox的數據綁定文本框

我有一堆文本框,我需要填充數據,例如在我的案例地址。我有一個組合框綁定到一個枚舉,並有一個值列表中的值從

家庭,辦公室,MainOffice,實驗室。等等。當我在組合框上進行選擇時,我需要在下面的文本框中填寫它的地址。我可以從對象X獲得起始地址,從對象Y獲得辦公地址,從Z獲得MainOffice。我如何使用組合框選擇來執行此條件數據綁定。請指教。

這些是我可以選擇

public enum MailToOptions 
{ 
    Home, 
    Office, 
    CorporateOffice, 
    Laboratory, 
} 



    <!-- Row 1 --> 
    <Label Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="5" Content="Mail To:" /> 
    <ComboBox Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="5" Name="MailToComboBox" 

    ItemsSource="{Binding Source={StaticResource odp}}"  
    SelectionChanged="HandleMailToSelectionChangedEvent" > 

    </ComboBox> 
    <!-- Agency ID --> 


    <!-- Name --> 
    <Label Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="5" Content="Name" /> 
    <TextBox Grid.Row="4" Grid.Column="0" Grid.ColumnSpan="5"> 
     <TextBox.Text> 
      <Binding Path="Order.Agency.PartyFullName" Mode="TwoWay" /> 
     </TextBox.Text> 
    </TextBox> 

    <!-- Row 2 --> 

    <!-- Address Line 1 --> 
    <Label Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="5" Content="Address 1" /> 
    <TextBox Grid.Row="7" Grid.Column="0" Grid.ColumnSpan="5"> 
     <TextBox.Text> 
      <Binding Path="Order.Agency.AddressLine1" Mode="TwoWay"  /> 
     </TextBox.Text> 
    </TextBox> 
+0

你可以發佈顯示到目前爲止你所擁有的一些代碼? –

+0

Benjamin,我剛更新了我的問題以顯示一些代碼 – gurrawar

回答

9

最好的方法是使你的ComboBox對象的項目,並綁定文本字段的ComboBox.SelectedItem

例如,選擇

<ComboBox x:Name="AddressList" ItemsSource="{Binding Addresses}" DisplayMemberPath="Name" /> 

<TextBox Text="{Binding SelectedItem.Street, ElementName=AddressList}" ... /> 
<TextBox Text="{Binding SelectedItem.City, ElementName=AddressList}" ... /> 
<TextBox Text="{Binding SelectedItem.State, ElementName=AddressList}" ... /> 
<TextBox Text="{Binding SelectedItem.ZipCode, ElementName=AddressList}" ... /> 

一個更簡潔的方法是設置DataContext任何面板持有文本框

<ComboBox x:Name="AddressList" ItemsSource="{Binding Addresses}" DisplayMemberPath="Name" /> 

<Grid DataContext="{Binding SelectedItem, ElementName=AddressList}"> 
    <TextBox Text="{Binding Street}" ... /> 
    <TextBox Text="{Binding City}" ... /> 
    <TextBox Text="{Binding State}" ... /> 
    <TextBox Text="{Binding ZipCode}" ... /> 
</Grid> 

您可以綁定組合框像一個ObservableCollection<Address>,或在代碼中手動設置ItemsSource後面。

我倒是建議約束力,但手動設置在後面的代碼會是這個樣子:

var addresses = new List<Addresses>(); 
addresses.Add(new Address { Name = "Home", Street = "1234 Some Road", ... }); 
addresses.Add(new Address { Name = "Office", Street = "1234 Main Street", ... }); 
... 
AddressList.ItemsSource = addresses; 
+0

使用'DisplayMemberPath'顯示selectedItem而不是使用dataTemplate設置itemTemplate幫助我 –