A better approach is to bind the controls to a view model and to integrate the logic there. See: Explain Combo Box Binding In MVVM - WPF.
As an example we create a window for editing of person data. It contains a combobox where the user can select a city. When a certain city is selected, a button is is displayed, otherwise it is hidden.
You could have a view model looking like this
public class PersonViewModel: INotifyPropertyChanged
{
private string _city;
public string City
{
get { return _city; }
set {
if (value != _city) {
_city = value;
OnPropertyChanged(nameof(City));
OnPropertyChanged(nameof(MyButtonVisibility));
}
}
}
public List<string> Cities { get; } = new List<string> { "Austin", "Boston", "Chicago"};
public Visibility MyButtonVisibility => City == "Boston"
? Visibility.Visible
: Visibility.Hidden;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// Other properties
private string _firstName;
public string FirstName
{
get { return _firstName; }
set {
if (value != _firstName) {
_firstName = value;
OnPropertyChanged(nameof(FirstName));
}
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set {
if (value != _lastName) {
_lastName = value;
OnPropertyChanged(nameof(LastName));
}
}
}
}
Note that it implements INotifyPropertyChanged. It has a Cities collection used to display the combobox items and a City property for the selected city.
We also need a property for the button visibility (MyButtonVisibility). Note that when the selected city changes, we also raise the PropertyChanged event for MyButtonVisibility to tell WPF to requery the button visibility.
In the window's constructor we assign the view model:
public MainWindow()
{
InitializeComponent();
DataContext = new PersonViewModel();
}
The XAML code for the combobox is
<ComboBox x:Name="citiesComboBox" HorizontalAlignment="Left" Margin="116,96,0,0"
VerticalAlignment="Top" Width="120"
ItemsSource="{Binding Path=Cities}"
SelectedItem="{Binding Path=City}"
/>
The XAML code for the button is
<Button Content="Button" HorizontalAlignment="Left" Margin="116,164,0,0"
VerticalAlignment="Top" Width="75"
Visibility="{Binding MyButtonVisibility}"
/>
By the magic of WPF binding, now the button appears or disappears automatically, when you select cities.