xamarin.forms - Xamarin Forms ToolbarItem 不会从 XAML 更改 IsEnabled

标签 xamarin.forms toolbaritems

我遇到了 ToolbarItem 的问题和 IsEnabled尝试使用触发器从 XAML 打开/关闭它时的属性。 ToolbarItem不支持触发器,所以我要做的是创建一个 Button (一个隐藏的)支持触发器然后绑定(bind)Button.IsEnabledToolbarItem.IsEnabled ;这是示例代码:

    <ContentPage.ToolbarItems>
        <ToolbarItem x:Name="tlbSave" Text="Save" Clicked="Handle_Clicked">
            <ToolbarItem.IsEnabled>
                <Binding Source="{x:Reference btnTest}" Path="IsEnabled" />
            </ToolbarItem.IsEnabled>
        </ToolbarItem>
    </ContentPage.ToolbarItems>

    <ContentPage.Content>

        <StackLayout Padding="10" VerticalOptions="CenterAndExpand">

            <Entry x:Name="txtTest" HorizontalOptions="FillAndExpand" />

            <Button x:Name="btnTest" Text="HIDDEN" IsEnabled="false" HorizontalOptions="FillAndExpand">
                <Button.Triggers>
                    <MultiTrigger TargetType="Button">
                        <MultiTrigger.Conditions>
                            <BindingCondition Binding="{Binding Source={x:Reference txtTest}, Path=Text.Length,
                                                           Converter={convert:IsPositiveIntegerConverter}}" Value="true" />
                        </MultiTrigger.Conditions>

                        <Setter Property="IsEnabled" Value="True" />
                    </MultiTrigger>
                </Button.Triggers>
            </Button>

        </StackLayout>

    </ContentPage.Content>

如果您尝试这段代码,您将看到 btnTesttxtTest.Text 时启用/禁用有一定的值(value)。但它不影响 tlbSave.IsEnabled属性(property)。

但是,当我设置 tlbSave.IsEnabled 时,这项工作在代码后面很完美。进入 btnText.PropertyChanged 事件处理程序
btnTest.IsVisible ,我只是为了测试目的而展示它。

关于如何处理这个问题的任何想法?

最佳答案

这是因为 ToolbarItem 的 IsEnabled 属性是 只读 .

如果您只是将 XAML 中工具栏项的 IsEnabled 属性设置为 false 或 true,您将在运行时收到以下异常。

System.InvalidOperationException: The BindableProperty "IsEnabled" is readonly.

如果你看看 Microsoft's documentation ,您会注意到您不能直接设置工具栏项的 IsEnabled 属性。

要禁用工具栏项,建议的方法是使用命令,它是 CanExecute。

关于xamarin.forms - Xamarin Forms ToolbarItem 不会从 XAML 更改 IsEnabled,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55089092/

相关文章:

c# - INavigationService 作为 MainPage 构造函数参数

c# - Xamarin Forms 访问 ListView

c# - 如何删除或隐藏特定页面中的工具栏项错误 : System. IndexOutOfRangeException:索引超出数组范围

ios - 将 UIButtonTypeDetailDisclosure 添加到 toolbarItems 导致运行时错误

c# - 设置 xamarin toolbaritems 的背景颜色

c# - Xamarin,使用来自 Xlabs 示例的地理定位

xamarin - 如何在 Xamarin.Forms 中接收来自服务器的响应

c# - 使用 content(body) 或多个参数的 restful API get 方法

android - 在 Xamarin.Forms 中复制下拉 ToolbarItem "More"

inheritance - Xamarin.Forms:使用所有页面扩展 CommonToolbarPage 类