如何使用存在于usercontrol后代码中的eventhandler以编程方式打开和关闭bottomappbar?

Joh*_*aib 1 c# xaml user-controls appbar windows-8

我有一个Windows 8应用程序(Xaml和C#):

我有一个包含在MainPage中的userControl.

在这个MainPage中,我已经包含了一个在RightClick和Windows + Z上完全正常运行的BottomAppBar.

我需要做的是从userControl中存在的图像上的事件处理程序(在usercontrol后面的代码中)打开BottomAppBar.我需要访问BottomAppBar才能使用属性IsOpen,但我无法这样做.任何提示?我错过了什么吗?

Xyr*_*oid 5

我给你最简单的例子,它可以指导你如何做到这一点.

正常方式

BlankPage4.xaml

<Page.BottomAppBar>
    <AppBar IsSticky="True" IsOpen="True">
        <Button Style="{StaticResource BackButtonStyle}" />
    </AppBar>
</Page.BottomAppBar>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <local:MyUserControl1 />
</Grid>
Run Code Online (Sandbox Code Playgroud)

MyUserControl1.xaml

<Grid>
    <Button Click="btnClose_CLick" Content="Close AppBar" />
</Grid>
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)