【问题标题】:Bind IsEnabled of button to IsChecked of toggle button UWP将按钮的 IsEnabled 绑定到切换按钮 UWP 的 IsChecked
【发布时间】:2019-02-21 18:37:47
【问题描述】:

我正在尝试将一个按钮的启用属性绑定到 UWP 中另一个按钮的选中属性。

    <CommandBar DefaultLabelPosition="Right" VerticalContentAlignment="Center">
            <AppBarButton Icon="Add" Label="Add Images" Command="{x:Bind ViewModel.AddImagesCommand}"/>
            <AppBarSeparator/>
            <AppBarToggleButton x:Name="buttonSelect" Label="Select"/>
            <AppBarButton Icon="SelectAll" Label="SelectAll" Click="{x:Bind gridViewInputImages.SelectAll}" IsEnabled="{x:Bind buttonSelect.IsChecked}"/>
        </CommandBar>

但是,我收到错误绑定分配无效:无法直接将类型“System.Nullable(System.Boolean)”绑定到“System.Boolean”。使用强制转换、转换器或函数绑定来更改类型

我想我可以通过绑定到 ViewModel 中的中间值来解决这个问题,但是有没有办法在 XAML 中做到这一点?

【问题讨论】:

    标签: uwp uwp-xaml


    【解决方案1】:

    像这样在 XAML 中使用它:

    <CommandBar
                DefaultLabelPosition="Right"
                VerticalContentAlignment="Center">
                <AppBarButton
                    Icon="Add"
                    Label="Add Images"
                    Command="{x:Bind ViewModel.AddImagesCommand}" />
                <AppBarSeparator />
                <AppBarToggleButton
                    x:Name="buttonSelect"
                    Label="Select" />
                <AppBarButton
                    Icon="SelectAll"
                    Label="SelectAll"
                    Click="{x:Bind gridViewInputImages.SelectAll}"
                    IsEnabled="{Binding IsChecked, ElementName=buttonSelect, Converter={StaticResource NullBoolConverter}}" />
            </CommandBar>
    

    使用这样的转换器:

    public class NullBoolConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            if (value == null)
                return false;
    
            return (bool)value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }
    

    在您的页面 StaticResources 中声明您的转换器:

    <converters:NullBoolConverter
            x:Key="NullBoolConverter"/>
    

    【讨论】:

      【解决方案2】:

      您不应将可为空的值绑定到 bool,因为 bool 不是空的。

      IsEnabled 值为bool,IsChecked 值为bool?。你应该写一个convert来把bool?转换成bool。

      【讨论】:

        猜你喜欢
        • 2015-07-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 2016-06-22
        • 2011-08-26
        • 1970-01-01
        • 2023-03-20
        • 2015-12-30
        相关资源
        最近更新 更多