繁体   English   中英

UWP XAML 自定义命令栏切换按钮

[英]UWP XAML Custom Command Bar Toggle Button

我正在尝试为 CommandBar 创建一个自定义 AppBarToggleButton,它将仅使用 XAML ThemeResource 作为最喜欢/不喜欢的按钮做出反应。 我希望它将图标从OutlineStart更改为SolidStar并将UnfavoriteFavorite的按钮更改为不喜欢的按钮,如下面的屏幕截图所示。 我想要达到的确切结果就在这里

这是这背后的代码: Github Gist

我的问题是,虽然此代码在XAML Studio应用程序中运行良好,但它会在Visual Studio 2017 Community中引发Uncaught exception 它在Visual Studio设计器中也可以正常工作。

我知道我可以通过类似的代码来实现相同的目标

private void ToggleFavorite_Checked(object sender, RoutedEventArgs e) {
    ToggleFavorite.Text = "Unfavorite";
    ToggleFavorite.Icon = new SymbolIcon(Symbol.SolidStar);
}
private void ToggleFavorite_Unchecked(object sender, RoutedEventArgs e) {
    ToggleFavorite.Text = "Favorite";
    ToggleFavorite.Icon = new SymbolIcon(Symbol.OutlineStar);
}

但这不是我想要的,我对 XAML 定制很感兴趣,我想完全按照 XAML 风格来做。

我该怎么做才能让它在Visual Studio 2017中工作?

编辑(05.03.2020) :修改我的代码后,我注意到Visual Studio将此行突出显示为错误

<Setter Target="Content.Foreground" Value="{ThemeResource AppBarToggleButtonForegroundPointerOver}"/>

发生这种情况是因为我在这里将ContentPresenter的名称从Content更改为ViewboxContentPresenter

<Viewbox x:Name="ContentViewbox" AutomationProperties.AccessibilityView="Raw" HorizontalAlignment="Stretch" Height="{ThemeResource AppBarButtonContentHeight}" Margin="{ThemeResource AppBarButtonContentViewboxCollapsedMargin}">
    <ContentPresenter x:Name="ViewboxContentPresenter" Foreground="{TemplateBinding Foreground}">
        <ContentPresenter.Content>
            <SymbolIcon Symbol="OutlineStar" />
        </ContentPresenter.Content>
    </ContentPresenter>
</Viewbox>

所以,这就是抛出Unhandled Exception的原因。 在重命名所有这些设置器的目标后,一切都开始按预期工作。

您可以使用VisualStateManager来实现您的要求。

使用StateTrigger绑定AppBarToggleButtonIsChecked属性。 选中按钮后使用Setter设置属性。

<Grid>
        <CommandBar VerticalAlignment="Bottom">
            <AppBarToggleButton x:Name="toggleBtn" Icon="UnFavorite" Label="UnFavorite"/>
        </CommandBar>

        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState x:Name="checkedbtn">
                    <VisualState.StateTriggers>
                        <StateTrigger IsActive="{Binding ElementName=toggleBtn, Path=IsChecked}"/>
                    </VisualState.StateTriggers>
                    <VisualState.Setters>
                        <Setter Target="toggleBtn.Icon" Value="Favorite"/>
                        <Setter Target="toggleBtn.Label" Value="Favorite"/>
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    </Grid>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM