简体   繁体   English

使用绑定的UWP应用程序显示/隐藏按钮

[英]UWP app show/hide Button using binding

I have a List view which shows the project names and some buttons for each project which do different actions like adding a comment viewing images for that project etc.. Depending on the project some projects will have some of these buttons disabled sometimes. 我有一个列表视图,其中显示了项目名称和每个项目的一些按钮,这些按钮执行不同的操作,例如添加评论以查看该项目的图像等。根据项目的不同,某些项目有时会禁用其中一些按钮。 And some buttons will not be visible in some projects. 并且某些按钮在某些项目中将不可见。 So there are two things I want to achieve using data binding in this code. 因此,我想在此代码中使用数据绑定实现两件事。

  1. Depending on some boolean variables of the ProjectModel, I need to change the visibility of the buttons. 根据ProjectModel的一些布尔变量,我需要更改按钮的可见性。 I tried this Binding a Button's visibility to a bool value in ViewModel but it doesn't seem to work on uwp. 我尝试了在ViewModel中将Button的可见性绑定到bool值,但是在uwp上似乎不起作用。

  2. For some projects I need to show a different colored image when that option is disabled. 对于某些项目,禁用该选项后,我需要显示不同的彩色图像。 So I need to change the ImageSource of ImageBrush depending on the boolean variables of the ProjectModel. 因此,我需要根据ProjectModel的布尔变量更改ImageBrush的ImageSource。 For that I tried this Change image using trigger WPF MVVM and those style triggers are not working for uwp. 为此,我使用触发器WPF MVVM尝试了此更改图像,并且这些样式触发器不适用于uwp。

Please let me know how to do these easily in a UWP app. 请让我知道如何在UWP应用中轻松完成这些操作。 This is my first UWP app and I am new to these concepts. 这是我的第一个UWP应用程序,我对这些概念并不陌生。

<ListView x:Name="stepsListView" Margin="10,0,0,0" RequestedTheme="Dark" FontSize="24" Background="{StaticResource procedure_app_white}" Foreground="Black" BorderThickness="1.5" BorderBrush="Transparent" ItemsSource="{Binding projectList}"  HorizontalAlignment="Left">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            </Style>
        </ListView.ItemContainerStyle>
        <!-- Item -->
        <ListView.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="0,0,0,1" BorderBrush="#c0c0c0">
                    <Grid Width="auto" HorizontalAlignment="Stretch" DataContextChanged="Grid_DataContextChanged" >
                        <Grid.RowDefinitions>
                            <RowDefinition Height="*"/>
                            <RowDefinition Height="50"/>
                        </Grid.RowDefinitions>
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="100"/>
                            <ColumnDefinition Width="100"/>
                        </Grid.ColumnDefinitions>
                        <TextBlock VerticalAlignment="Center" FontSize="30" Grid.Row="0" Grid.ColumnSpan="7" Text="{Binding projectName}" Foreground="{StaticResource procedure_app_orange_text }" />

                        <Button x:Name="warningButton" Width="40" Height="40" Grid.Column="1"  Grid.Row="1" Tag="{Binding projectId}" Click="warningButtonClick" Foreground="{StaticResource procedure_app_orange_text }">
                            <Button.Background>
                                <ImageBrush ImageSource="Asset/step_ncwr.png">
                                </ImageBrush>
                            </Button.Background>
                        </Button>
                        <Button x:Name="commentButton" Width="40" Height="40" Grid.Column="2"   Grid.Row="1"  Tag="{Binding projectId}" Click="CommentButtonClick" Foreground="{StaticResource procedure_app_orange_text }" IsTapEnabled="True">
                        <Button.Background>
                            <ImageBrush ImageSource="Asset/step_comment.png">
                            </ImageBrush>
                        </Button.Background>
                        </Button>
                        <Button x:Name="imageButton" Width="40" Height="40" Grid.Column="3"  Grid.Row="1"  Tag="{Binding projectId}" Click="ImageButtonClick" Foreground="{StaticResource procedure_app_orange_text }">
                            <Button.Background>
                                <ImageBrush ImageSource="Asset/step_image.png">
                                </ImageBrush>
                            </Button.Background>
                        </Button>
                    </Grid>
                </Border>
            </DataTemplate>
        </ListView.ItemTemplate>

The Visibility property is not of type bool so that's why you cannot bind it to the Boolean property in your ViewModel directly. Visibility属性的类型不是bool ,这就是为什么您不能直接将其绑定到ViewModel中的Boolean属性。

You need to do so though a converter. 您需要通过转换器来执行此操作。 As the name sais, a Converter is a class that helps you convert from one type to another in for Bindings to work. 顾名思义,Converter是一个类,可帮助您从一种类型转换为另一种类型,以使绑定起作用。 In your case, you need to convert a boolean value of true to a Visibility value of Visible . 在您的情况下,您需要将true的布尔值转换为Visible的Visibility值。

There is a built-in converter in UWP but I will show you how to create one since you will probably need to write other converters in the future: UWP中有一个内置转换器,但我将向您展示如何创建一个转换器,因为将来您可能需要编写其他转换器:

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Data;

namespace YourNamespace
{
    public class BooleanToVisibilityConverter : IValueConverter
    {
        public Visibility OnTrue { get; set; }
        public Visibility OnFalse { get; set; }

        public BooleanToVisibilityConverter()
        {
            OnFalse = Visibility.Collapsed;
            OnTrue = Visibility.Visible;
        }

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var v = (bool)value;

            return v ? OnTrue : OnFalse;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            if (value is Visibility == false)
                return DependencyProperty.UnsetValue;

            if ((Visibility)value == OnTrue)
                return true;
            else
                return false;
        }
    }
}

The converter allows you to convert Boolean values to Visibility values and by default will convert True to Visibility.Visible and False to Visibility.Collapsed , but it is configurable as you'll see below. 该转换器允许您将布尔值转换为Visibility值,并且默认情况下会将True转换为Visibility.Visible ,将False转换为Visibility.Collapsed ,但是它是可配置的,如下所示。

Next you need to declare your converter in your XAML. 接下来,您需要在XAML中声明转换器。 In the Page or UserControl you need to perform this steps: 在页面或用户控件中,您需要执行以下步骤:

  1. Declare the converter Namespace (use the same namespace you used when creating the converter class 声明转换器名称空间(使用创建转换器类时使用的相同名称空间

     xmlns:converters="using:YourNamespace" 
  2. Instantiate the converter in your Page / UserControl Resources 在您的页面/ UserControl资源中实例化转换器

    <Page.Resources> <converters:BooleanToVisibilityConverter x:Key="bool2vis"/> <converters:BooleanToVisibilityConverter x:Key="bool2visInverse" OnTrue=Collapsed, OnFalse=Visible/> </Page.Resources>

  3. Use your converter in your binding: 在绑定中使用转换器:

    <Button x:Name="warningButton" Width="40" Height="40" Grid.Column="1" Grid.Row="1" Tag="{Binding projectId}" Click="warningButtonClick" Foreground="{StaticResource procedure_app_orange_text }" Visibility="{Binding IsVisible, Converter={StaticResource bool2vis}}">

So I think what you're going to want to do is modify the button's template. 因此,我认为您要做的就是修改按钮的模板。

If you look at the MSDN article on Button Styles and Tempaltes you will see the default Button Style. 如果您查看有关按钮样式和模板MSDN文章,您将看到默认的按钮样式。

Inside this default style you'll see this 在此默认样式内,您将看到此

  <VisualState x:Name="Disabled">
     <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid"
                                       Storyboard.TargetProperty="Background">
              <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlBackgroundBaseLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}" />
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                                   Storyboard.TargetProperty="BorderBrush">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlDisabledTransparentBrush}" />
        </ObjectAnimationUsingKeyFrames>
     </Storyboard>
  </VisualState>

See where it say's Disabled? 看到在哪里说残疾人? Everything inside of here defines how the button looks when it is disabled. 此处的所有内容都定义了禁用按钮时的外观。 I would research how to retemplate a button and then mess around with this style. 我将研究如何重新设计按钮,然后弄乱这种样式。

Start here Xaml Custom Styles in UWP 从此处开始UWP中的Xaml自定义样式

To hide a ui element just do this: 要隐藏ui元素,只需执行以下操作:

this.MyComponent.Visibility = Visibility.Collapsed;

And to make it visible do this: 并使其可见:

this.MyComponent.Visibility = Visibility.Visible;

This is almost identical to passing a true, false, and what is most people who read this title will actually be looking for. 这几乎与传递真假有关,而阅读此标题的大多数人实际上是在寻找什么。

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

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