How to find and replace items in a WPF ComboBox

The XAML code listed below creates a Window with two TextBox controls, a Button control, and a ComboBox control. The Find and Replace button click event reads the Find TextBox and changes the Replace with text in the ComboBox.

FindReplaceComboBoxItem.gif


XAML code for Window:

<Window x:Class="ComboBoxSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">

    <Canvas Name="LayoutRoot">
       
        <ComboBox x:Name="ComboBox1" Width="250" Height="30"
                  Canvas.Top="132" Canvas.Left="10">                     
            <ComboBoxItem Name="cbi1">C# Corner</ComboBoxItem>
            <ComboBoxItem Name="cbi2">VB.NET Heaven</ComboBoxItem>
            <ComboBoxItem Name="cbi3">MSDN</ComboBoxItem>
        </ComboBox>
        <Button Canvas.Left="138" Canvas.Top="88" Height="28" Name="FindReplaceButton" Width="123"
                Click="FindReplaceButton_Click">
            Find and Replace
        </Button>
        <TextBox Canvas.Left="137" Canvas.Top="12" Height="28" Name="FindTextBox" Width="121" />
        <TextBox Canvas.Left="138" Canvas.Top="48" Height="31" Name="ReplaceWithTextBox" Width="123" />
        <Label Canvas.Left="37" Canvas.Top="12" Height="27" Name="label1" Width="94">Find</Label>
        <Label Canvas.Left="38" Canvas.Top="52" Height="27" Name="label2" Width="94">Replace with</Label>
    </Canvas>
</Window>


The FindReplace button click event handler.


private void FindReplaceButton_Click(object sender, RoutedEventArgs e)
{
    foreach (var item in ComboBox1.Items)
    {
        if (((ComboBoxItem)item).Content.ToString() == FindTextBox.Text)
        {
            ((ComboBoxItem)item).Content = ReplaceWithTextBox.Text;
            return;               
        }
    }
}