我正在使用Prism(MVVM)与WPF合作。我想设置visibililty 来自ViewModel calss的StackPanel。 StackPanel的可见性是 绑定如:
<StackPanel x:Name="spVisibility" Orientation="Horizontal"
Visibility="{Binding spVisibility, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}">
我查看模型类,如:
public class SearchId : BindableBase, INotifyPropertyChanged
{
private Visibility _visibility = Visibility.Collapsed;
private DelegateCommand<object> searchCommand;
public event PropertyChangedEventHandler PropertyChanged;
public SearchId()
{
searchCommand = new DelegateCommand<object>(this.SearchData);
}///
public Visibility spVisibility
{
get { return _visibility; }
set
{
if (!string.Equals(_visibility, value))
{
_visibility = value;
RaisePropertyChanged("spVisibility");
}
}
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs (propertyName));
}
}
private async void SearchData(object parameter)
{
_visibility = Visibility.Visible;
}
}
但这不起作用。请帮帮我。
答案 0 :(得分:2)
_visibility = Visibility.Visible
设置私有属性而不是使用公共属性,因此绕过了RaisePropertyChanged("spVisibility")
。您需要使用spVisibility = Visibility.Visible
。
答案 1 :(得分:1)
如果您使用MVVM,我建议使用布尔值而不是可见性。 MVVM的整个目的是从DataLogic中分离View Logic。
查看逻辑:
<StackPanel Orientation="Horizontal"
Visibility="{Binding ShowStackPanel, Converter={StaticResource BooleanToVisibilityConverter}}">
使用转换器将boolan转换为Visibility属性.BnoleanToVisibilityConverter是.NET的一部分,无需在xaml中手动定义即可引用。
public class SearchId : BindableBase, INotifyPropertyChanged
{
private bool _showStackPanel;
private DelegateCommand<object> searchCommand;
public event PropertyChangedEventHandler PropertyChanged;
public SearchByIDVM()
{
searchCommand = new DelegateCommand<object>(this.SearchData);
}///
public bool ShowStackPanel
{
get { return _showStackPanel; }
set
{
if (!Equals(_showStackPanel, value))
{
_showStackPanel= value;
RaisePropertyChanged("ShowStackPanel");
}
}
}
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs (propertyName));
}
}
private async void SearchData(object parameter)
{
ShowStackPanel= true;
}
}