kirchhoff
kirchhoff

Reputation: 3

Obtain ComboBox Items from several TextBoxes

In WPF, how do I place Text of TextBox into Items of a ComboBox? I have seen a question that does the opposite, meaning binding selected Item in ComboBox to TextBox. Here is my scenario, I have a tabcontrol, each tabPage contains TextBoxes. I have already completed data binding for validating the TextBoxes' Text. Now, I need to make the ComboBox outside the tabControl, to display validated Text from TextBoxes.

<Grid>
<TabControl>
<TabItem>
<TextBox />
<TextBox>
  ...
</TextBox>
</TabItem>
</TabControl>
<ComboBox   />
<ComboBox   />
</Grid>

I'm a fresh newbie to WPF. I may need a lot of references for further reading regarding the solution. Thanks.

Upvotes: 0

Views: 121

Answers (1)

Eirik
Eirik

Reputation: 4205

Here's a simple solution that will display the text of the four textboxes in the combobox:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <TextBox Name="tb0" />
    <TextBox Name="tb1" Grid.Row="1" />
    <TextBox Name="tb2" Grid.Row="2" />
    <TextBox Name="tb3" Grid.Row="3" />
    <ComboBox Grid.Row="4">
        <ComboBoxItem IsSelected="True">
            <TextBlock Text="{Binding ElementName=tb0, Path=Text}" />
        </ComboBoxItem>
        <ComboBoxItem>
            <TextBlock Text="{Binding ElementName=tb1, Path=Text}" />
        </ComboBoxItem>
        <ComboBoxItem>
            <TextBlock Text="{Binding ElementName=tb2, Path=Text}" />
        </ComboBoxItem>
        <ComboBoxItem>
            <TextBlock Text="{Binding ElementName=tb3, Path=Text}" />
        </ComboBoxItem>
    </ComboBox>
</Grid>

Edit: To hide the items in the combobox when they're empty you can use a converter and check if the text is empty.

Converter:

public abstract class BaseConverter : MarkupExtension
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

public class StringToVisibilityConverter : BaseConverter, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value.ToString() != string.Empty ? Visibility.Visible : Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

Add the converter as a resource:

<Window.Resources>
    <TestProject:StringToVisibilityConverter x:Key="stringToVisibilityConverter" />
</Window.Resources>

Use the converter:

<ComboBoxItem>
    <TextBlock Text="{Binding ElementName=tb3, Path=Text}" Visibility="{Binding ElementName=tb3, Path=Text, Converter={StaticResource stringToVisibilityConverter}}" />
</ComboBoxItem>

Upvotes: 1

Related Questions