问题
I have a View which contains the userprofile of the current user. The view contains a viewmodel with a two-way binding to the single attributes like username or email adress. The view also has a behaviour, which validates the input and shows an error, of the input is not valid. Because of the two-way binding, the viewmodel updates the value even if the behavior says the input is wrong. I need to solve that.
My current approach is to use include the behavior in the viewmodel as a attribute. So I can access the attributes of the behavior in the setter of the attributes in the viewmodel. So I cant stop the update to the wrong inputs. But I can not get access the behavior from my viewmodel in the xaml of the view. Is that a way I can do it at all?
My next approach would be to pass the "isValid" attribute of the behavior to the viewmodel. But here again, I don't know how to do it, is it possible at all?
Last approach would be to create a command in the viewmodel, binding it to a new button in the userprofile, using a one-way binding and somehow pass the inputs from the view to the command and updateing the userprofile.
May be here is someone who can help me?
EDIT: I post some code:
This is a single entry with my behavior:
<Entry x:Name="phoneNumber" Text="{Binding TelephoneNum, Mode=TwoWay}">
<Entry.Behaviors>
<behaviors:TelNumBehavior x:Name="NumValidatorUser"/>
</Entry.Behaviors>
</Entry>
The TelNumBehavior:
public class TelNumBehavior : Behavior<Entry>
{
...
public static readonly BindablePropertyKey IsVisiblePropertyKey =
BindableProperty.CreateReadOnly("IsVisible", typeof(bool), typeof(TelNumBehavior), false);
public static readonly BindableProperty IsVisibleProperty = IsVisiblePropertyKey.BindableProperty;
...
public bool IsVisible
{
get { return (bool) this.GetValue(IsVisibleProperty); }
set
{
this.SetValue(IsVisiblePropertyKey, value);
}
}
...
(OnAttachedTo, OnDetachingFrom)
...
private void bindable_TextChanged(object sender, TextChangedEventArgs e)
{
Entry entry = sender as Entry;
this.IsVisible = (entry.Text == "")
? true
: (Regex.IsMatch(e.NewTextValue, mobileRegex) || Regex.IsMatch(e.NewTextValue, fixedLineRegex));
entry.TextColor = this.IsVisible ? Color.Default : Color.Red;
}
To sum it up: I use that behavior for validation of some inputs. But the viewmodel does not know if the inputs are correct or not. And this is currently my problem. I dont know how to inform the viewmodel about the state of the inputs.
}
来源:https://stackoverflow.com/questions/52567801/xamarin-view-with-viewmodel-and-behaviour