我有一个带有一些项目和文本块的组合框,我希望如果用户从组合框中选择让我们坐着Item3
,那么文本块将是可见的,否则是不可见的。
我想用mvvm做这个(我是这个架构的新手),我添加了一些MessageBox来检查它是否进入if
条件并显示MessageBox但文本块总是不可见的,这里是我的代码:
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");
}
}
}
答案 0 :(得分:1)
您需要告诉视图在viewmodel中属性的值已更改,并且应该读取该值。 在viewmodel中实现inotifypropertychanged。 在这里提高房产价格:
Public Visibility VersionVisibility
{
get { return _isEnable; }
set { _isEnable = value; RaisePropertyChanged();}
}
这是一个基本的viewmodel类,你可以从中继承你的viewmodel。
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}