1

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

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

在这个 MainPage 中,我包含了一个在 RightClick 和 Windows+Z 上完全运行的 BottomAppBar。

我需要做的是从用户控件中存在的图像上的事件处理程序(在用户控件返回代码中)打开 BottomAppBar。我需要访问 BottomAppBar 才能使用 IsOpen 属性,但我无法这样做。有什么提示吗?我错过了什么吗?

4

1 回答 1

5

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

正常方式

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

视图模型.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));
        }
    }
}
于 2013-10-03T17:06:11.150 回答