0

I have a combobox with some items and a textblock, I want that if the user choose let's sat Item3 from the combobox then the textblock will be visible, and unvisible otherwise.

I wanna do it with mvvm (I'm new with this architecture), I added some MessageBox to check if it goes into the if condition and it shows the MessageBox but the textblock is always unvisible, here is my code:

XAML:

<ComboBox x:Name="product_combobox" IsEditable="False" IsReadOnly="True"  Height="24" Margin="155,106,155,0"  HorizontalAlignment="Center" VerticalAlignment="Top"  Width="210" ItemsSource="{Binding MyItems}" SelectedIndex="{Binding YourIndexProperty}" SelectedItem="{Binding SelectedItem}" />

<TextBlock x:Name="version_textBlock" Visibility="{Binding VersionVisibility}"  Height="20" Margin="155,144,155,0" TextWrapping="Wrap" HorizontalAlignment="Center" Text="Select Sasa version:" VerticalAlignment="Top" FontFamily="Moire ExtraBold" RenderTransformOrigin="0.582,0.605" Width="210" FontWeight="Bold" />

ViewModel.cs:

public ObservableCollection<string> MyItems { get; set; }
        public string _mySelectedItem;
        public Visibility _isEnable;

        public Page1VM()
        {
            this.DisplayMessageCommand = new RelayCommand(this.DisplayMessage);
            MyItems = new ObservableCollection<string>()
            {
                 "--Product--",
                "Item1",
                "Item2",
                "Item3"
            };
            _mySelectedItem = "--Product--";
            _isEnable = Visibility.Hidden;//<--------this for hiding the textblock when page load
        }

public Visibility VersionVisibility
        {
            get { return _isEnable; }
            set { _isEnable = value; }
        }



        public string SelectedItem
        {
            get { return _mySelectedItem; }
            set
            {
                _mySelectedItem = value;

                if (value.Equals("Item3"))
                {
                    VersionVisibility = Visibility.Visible;

                    MessageBox.Show("test");
                }
            }
        }
Flufy
  • 309
  • 2
  • 15

1 Answers1

1

You need to tell the view that the value of a property has changed in the viewmodel and it should go read that new value. Implement inotifypropertychanged in your viewmodel. Raise propertychanged in here:

Public Visibility VersionVisibility
        {
            get { return _isEnable; }
            set { _isEnable = value; RaisePropertyChanged();}
        }

Here's a base viewmodel class you could inherit your viewmodel from.

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
Andy
  • 11,864
  • 2
  • 17
  • 20