如何以编程方式打开和关闭bottomappbar使用中存在的用户控件后面的代码事件处理程序?(how

2019-10-18 17:31发布

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

我有一个是包含在一个的MainPage用户控件。

在此我的MainPage已经包括一个BottomAppBar是上右击和Windows + Z充分发挥作用。

我需要做的是从事件处理程序(在用户控件后面的代码)存在于用户控件的图像上打开BottomAppBar。 我需要访问BottomAppBar以使用属性ISOPEN,但我不能够这样做。 任何提示? 我失去了什么?

Answer 1:

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

正常的方式

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));
        }
    }
}


文章来源: how to programatically open and close bottomappbar using a eventhandler that exist in a usercontrol back code?