【发布时间】:2018-07-11 14:45:11
【问题描述】:
我正在使用下面的转换器代码
namespace someAssembly.Converters
{
public class ValidateTextLengthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return (int)value != 0;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return (bool)value ? 1 : 0;
}
}
}
这是我的 Xaml
命名空间:
xmlns:converter="clr-namespace:someNamepsace.someAssembly.Converters;assembly=someAssembly"
资源:
<ContentPage.Resources>
<ResourceDictionary>
<converter:ValidateTextLengthConverter x:Key="validateLength" />
</ResourceDictionary>
</ContentPage.Resources>
用法:(编辑我添加了转换器引用的文本框)
<StackLayout HorizontalOptions="FillAndExpand">
<Label Text="Name:" />
<Entry x:Name="txtName" Text="{Binding Name}" HorizontalOptions="FillAndExpand" />
</StackLayout>
<Button x:Name="btnSave" Text="Save"
Command="{Binding SaveCommand}"
HorizontalOptions="EndAndExpand"
BackgroundColor="{x:Static local:ColorResources.ButtonColorTransparent}"
IsEnabled="{Binding Source={x:Reference txtName},
Path=Text.Length,
Converter={StaticResource validateLength}}" />
我的主要目的是在文本框长度仍为零时禁用按钮。似乎 Converter 或 IsEnabled 没有触发。我的代码有问题吗?
【问题讨论】:
-
按钮有什么作用?它在哪里行动?我建议将命令绑定到按钮并编写其 CanExecute 以检查条目文本的长度。这样你就可以在视图模型中有逻辑,你不需要转换器来禁用按钮
-
我省略了按钮功能,但它绑定到我使用 ViewModelContext 而不是通过 Clicked 事件背后的表单代码的命令。
-
哦,我明白你的意思了,你能给我一个 CanExecute 的 sn-ps 吗?我正在使用棱镜
-
类似:private bool CanExecuteMyCommand() { if (string.IsNullOrEmpty(Name)) return false return true;并在名称设置器中添加“MyCommand?.RaiseCanExecuteChanged();”
标签: c# android ios xamarin.forms converter