1

当我的视图模型很忙时,我想禁用搜索栏。我的观点有以下 xaml(部分观点):

<SearchBar x:Name="searchBar" TextChanged="OnSearchQueryChanged" Grid.Row="0"  IsEnabled="{Binding IsBusy}"/>
<ActivityIndicator x:Name="progress" IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}"/>

两个元素都绑定到同一个属性,但是当我的 ViewModel 引发 IsBusy = false 时,SearchBar 保持禁用状态。同时进度变得隐藏。

这里有什么问题?

4

1 回答 1

6

您想要的是在查看模型属性时将SearchBar.IsEnabled属性设置为,反之亦然trueIsBusyfalse

您现在正在做的是IsEnabled在您的 vie 模型不再忙(IsBusy为假)时禁用(设置为假)搜索栏。

为此,您需要一个转换器,一个返回 true 表示 false 和 false 表示 true 的转换器:

public class NotConverter:IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value.GetType () == typeof(bool))
            return !((bool)value);
        return value;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }
}

为了在 xaml 中的绑定中使用它,让我们将它的一个实例作为资源包含在包装 xaml 片段的容器中(假设它是 a ContentPage),然后我们可以在{Binding}标记扩展中引用该转换器:

<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:local="clr-namespace:YourNamespace;assembly=YourAssemblyName">
    <ContentPage.Resources>
        <ResourceDictionary>
            <local:NotConverter x:Key="notConverter"/>
        </ResourceDictionary>
    </ContentPage.Resources>
    <ContentPage.Content>
        <StackLayout Orientation="Vertical">
            <SearchBar x:Name="searchBar" TextChanged="OnSearchQueryChanged" Grid.Row="0"  IsEnabled="{Binding IsBusy, Converter={StaticResource notConverter}}"/>
            <ActivityIndicator x:Name="progress" IsRunning="{Binding IsBusy}" IsVisible="{Binding IsBusy}"/>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
于 2014-06-20T07:29:14.757 回答