Home > other >  EventHandler in WPF - Change in one element affects another
EventHandler in WPF - Change in one element affects another

Time:03-21

I have a stackpanel with a TextBlock and a ComboxBox and the I have a TextBox acting as a search field.

<StackPanel Grid.Row="1" Grid.Column="2">
    <TextBlock Text="Group Filter" Margin="7,0,0,0"/>
    <ComboBox Text ="{Binding GroupFilter}" Height="30" Width="130" Margin="0,4,0,0" 
        Padding="5" IsSynchronizedWithCurrentItem="True"
        ItemsSource="{Binding Source={StaticResource GroupFilterEnum}}"
    </ComboBox>
</StackPanel>

<TextBox Text="{Binding SingleFilter, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Grid.Row="1" Grid.Column="3" Height="30" Width="140" Margin="0,20,0,0" Padding="5" materialDesign:HintAssist.Hint="Search single Id...">
</TextBox>

So basically I have a data set and what you can do is you can filter the data based on either a predefined setting from theGroupFilterEnum or you can enter a filter value yourself in the TextBox.

What I try to do is:

When the TextBox is empty things should just be as they are. When the TextBox has a value I would like to add the following to the ComboBox to indicate that the ComboBox is inactive when there is a value in the TextBox:

IsEditable="False" 
IsHitTestVisible="False" 
Focusable="False" 
Foreground="{StaticResource MaterialDesignBodyLight}" 

I have tried to make an TextChanged EventHandler for the TextBox like:

private void textChangedEventHandler(object sender, TextChangedEventArgs args)
{
    var text = sender.ToString().Replace("System.Windows.Controls.TextBox: ", "");

    if (!string.IsNullOrWhiteSpace(text))
    {

    }
} 

But I don't really know how to refer to the ComboBox from this EventHandler. I am fairly new to this, so I haven't reallty done a lot of EventHandlers. Is this the way to do it? If yes, could someone please help me with the Eventhandler? Or maybe there is a better way? Directly in the xaml file maybe?

All help is highly appreciated and please let me know if additional information is needed.

Thanks in advance.

CodePudding user response:

You could bind the ComboBox properties you want to change to the Text property of the TextBox using a converter that you would need to implement (here is the example).

<TextBox x:Name="MyTextBox"/>
<ComboBox Focusable="{Binding ElementName=MyTextBox, Path=Text, Converter={StaticResource EmptyStringToBooleanConverter}}">

CodePudding user response:

If you want a control that can be used like a textBox or comboBox, you are not in the good way.

The comboBox control have a property IsEditable which permit to write or select a value.

Try this : <ComboBox IsEditable="True"/>

Else, you can give a name to your control and you will able to get it in your code behind by typing his name.

The result here : Result (And I'm sorry for my english, I'm french).

  • Related