基于WPF Combobox的数据绑定文本框

时间:2012-06-25 16:21:03

标签: wpf data-binding combobox textbox conditional

我一直试图找到解决方案,但无法在线找到相关答案。

我有一堆文本框需要填充数据,例如在我的案例地址中。我有一个绑定到枚举的组合框,并有一个值列表可供选择

家庭,办公室,MainOffice,实验室。当我在组合框上做出选择时,我需要在下面的文本框中填充其地址。我可以从对象X获取Home地址,从Object Y获取Office地址,从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>

1 个答案:

答案 0 :(得分: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包含TextBoxes

<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>

您可以将ComboBox绑定到类似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;