我试图隐藏第2页上的按钮,点击Page1 上的按钮,但似乎无法正常工作。
第1页:btnRemove
第2页:btnEdit
以下是我正在尝试的代码。
private void btnRemove_Click(object sender, RoutedEventArgs e)
{
Uri uri = new Uri("Page2.xaml", UriKind.Relative);
this.NavigationService.Navigate(uri);
Page2 page = new Page2();
page.btnEdit.Visibility = Visibility.Hidden;
}
我做错了什么?
答案 0 :(得分:1)
转到您的XAML代码,通过添加以下内容来更改按钮定义
Visibility="{binding ButtonVisibility}"
创建一个名为ButtonViewModel.cs的新类,这里是代码
class ButtonViewModel: INotifyPropertyChanged
{
public ButtonViewModel(Visibility visibility)
{
_buttonVisibility = visibility;
}
private Visibility _buttonVisibility ;
public Visibility ButtonVisibility
{
get { return _buttonVisibility; }
set
{
_buttonVisibility = value;
OnPropertyChanged("ButtonVisibility");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string p)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(p));
}
}
在page2.cs中添加此构造函数
public Page2(Visibility visibilty)
{
InitializeComponent();
DataContext = new ButtonViewModel(visibilty);
}
public Page2()
{
InitializeComponent();
DataContext = new ButtonViewModel(Visibility.Visible);
}
转到按钮事件处理程序并添加此代码
NavigationWindow nvw = new NavigationWindow();
nvw.Content = new Page1(Visibility.Collapsed);
nvw.Show();
它正在和我一起工作