我有一个Windows 8应用程序(Xaml和C#):
我有一个包含在MainPage中的userControl。
在此主页中,我包含了一个BottomAppBar,它在RightClick和Windows + Z上可以正常运行。
我需要做的是从userControl中存在的图像上的事件处理程序(在usercontrol反向代码中)打开BottomAppBar。我需要访问BottomAppBar才能使用属性IsOpen,但是我不能这样做。有什么提示吗?我想念什么吗?
最佳答案
我给你最简单的例子,它可以指导你如何做。
正常方式
BlankPage4.xaml
<Page.BottomAppBar>
<AppBar IsSticky="True" IsOpen="True">
<Button Style="{StaticResource BackButtonStyle}" />
</AppBar>
</Page.BottomAppBar>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<local:MyUserControl1 />
</Grid>
MyUserControl1.xaml
<Grid>
<Button Click="btnClose_CLick" Content="Close AppBar" />
</Grid>
MyUserControl1.xaml.cs
private void btnClose_CLick(object sender, RoutedEventArgs e)
{
var isOpen = ((AppBar)((BlankPage4)((Grid)this.Parent).Parent).BottomAppBar).IsOpen;
if (isOpen)
{
((AppBar)((BlankPage4)((Grid)this.Parent).Parent).BottomAppBar).IsOpen = false;
}
else
{
((AppBar)((BlankPage4)((Grid)this.Parent).Parent).BottomAppBar).IsOpen = true;
}
}
MVVM方式
BlankPage4.xaml
<Page.BottomAppBar>
<AppBar IsSticky="True" IsOpen="{Binding IsOpenBottomBar}">
<Button Style="{StaticResource BackButtonStyle}" />
</AppBar>
</Page.BottomAppBar>
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<local:MyUserControl1 />
</Grid>
MyUserControl1.xaml.cs
private void btnClose_CLick(object sender, RoutedEventArgs e)
{
var isOpen = (this.DataContext as ViewModel).IsOpenBottomBar;
if (isOpen)
{
(this.DataContext as ViewModel).IsOpenBottomBar = false;
}
else
{
(this.DataContext as ViewModel).IsOpenBottomBar = true;
}
}
ViewModel.cs
public class ViewModel : INotifyPropertyChanged
{
private bool _IsOpenBottomBar;
public bool IsOpenBottomBar
{
get
{
return _IsOpenBottomBar;
}
set
{
_IsOpenBottomBar = value;
OnPropertyChanged("IsOpenBottomBar");
}
}
public ViewModel()
{
_IsOpenBottomBar = true;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
关于c# - 如何使用用户控件返回代码中存在的事件处理程序以编程方式打开和关闭bottomappbar?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19162445/