![](/img/trans.png)
[英]Xamarin.Forms Data bind Button.CommandParameterProperty to Entry.Text in Code Behind
[英]Xamarin: Get bound property of Entry.Text from event handler in code behind
我的代碼的非常簡化的版本:
視圖模型:
public class ViewModel
{
public ObjectViewModel {get; set;}
}
public class ObjectViewModel
{
public string MyString {get; set;}
public bool MyStringIsValid {get; set;}
}
Xml:
<Entry Text="{Binding ObjectViewModel.MyString}" TextChanged="Entry_TextChanged"/>
<Label Text="Valid!" IsVisible="{Binding ObjectViewModel.MyStringIsValid}"/>
在我后面的代碼中,我希望能夠通過執行以下操作來獲取 Entry.Text 的綁定屬性:
void Entry_TextChanged(object sender, TextChangedEventArgs e)
{
//Psuedocode
//ObjectViewModel ovm = (sender as Entry).Text.Binding.Source;
}
我想這樣做的原因是對“MyString”執行驗證並在必要時更改其“MyStringIsValid”屬性。 我的問題是我該怎么做,如果不可能,你能推薦一個更好的方法嗎?
在我的實際代碼中,我使用 INotifyPropertyChanged 根據 viewModel 更改更新視圖,但為簡潔起見,我省略了這一點。
謝謝!
我想你只需要一個轉換器。 我不知道為什么您需要維護一個屬性來根據文本的驗證更改 IsVisible。 以下代碼適用於您提到的類似場景。
<!--Declare the namespace at the top of the XAML-->
xmlns:c="clr-namespace:Demo.Helper"
<!--Register your Converter in the Resources-->
<ContentPage.Resources>
<ResourceDictionary>
<c:TextToBoolConverter x:Key="textToSpeechConverter" />
</ResourceDictionary>
</ContentPage.Resources>
<Entry x:Name="entry1" Text="{Binding ObjectViewModel.MyString}" />
<Label Text="Valid!" IsVisible="{Binding Text, Source={x:Reference entry1}, Converter={StaticResource textToSpeechConverter}}"/>
下面是我測試的轉換器代碼。
public class TextToBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string stringValue = value?.ToString();
if (!string.IsNullOrEmpty(stringValue))
return true;
return false;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.