简体   繁体   English

Xamarin.Forms DataTrigger不起作用

[英]Xamarin.Forms DataTrigger not working

I'm trying to set DataTrigger on my control in Xamarin.Forms, but I cannot get it working. 我试图在Xamarin.Forms的控件上设置DataTrigger,但无法使其正常工作。

I have Property in ViewModel with OnPropertyChange execution for bool IsValid 我在ViewModel中有属性,可以对Bos bool IsValid执行OnPropertyChange执行

I have tried: 我努力了:

DataTrigger in Xaml: Xaml中的DataTrigger:

<customControls:NumericTextBox
    Grid.Row="0" Grid.Column="2"
    Text="{Binding StringValue, Mode=TwoWay}"
    IsEnabled="{Binding IsEditable}"
    XAlign="End">
  <customControls:NumericTextBox.Style>
    <Style TargetType="customControls:NumericTextBox">
      <Style.Triggers>
        <DataTrigger TargetType="customControls:NumericTextBox" Binding="{Binding IsValid}" Value="true">
          <Setter Property="TextColor" Value="Red"/>
        </DataTrigger>
      </Style.Triggers>
    </Style>
  </customControls:NumericTextBox.Style>
</customControls:NumericTextBox>

Getting exception: The Property TargetType is required to create a Xamarin.Forms.DataTrigger object. 获取异常: The Property TargetType is required to create a Xamarin.Forms.DataTrigger object.

DataTrigger in Control: DataTrigger处于控制状态:

_item = new DataTrigger(typeof(NumericTextBox));
_item.Binding = new Binding("IsValid",BindingMode.Default,new NegativeBooleanConverter());
_item.Value = true;
Setter s = new Setter();
s.Property = TextColorProperty;
s.Value = Color.Red;
_item.Setters.Add(s);
this.Style.Triggers.Add(_item);

Exception: Exception has been thrown by the target of an invocation. 异常: Exception has been thrown by the target of an invocation.

I have tried also changing line : this.Style.Triggers.Add(_item); 我也尝试过更改行: this.Style.Triggers.Add(_item); to this.Triggers.Add(_item); this.Triggers.Add(_item); . This wasn't raising exception, but it just didn't worked. 这并没有引发异常,但是没有奏效。

In this last try, it even hits converter, but does not change TextColor of Control. 在这最后的尝试中,它甚至命中了转换器,但没有更改Control的TextColor。

Am I doing something wrong? 难道我做错了什么? How to handle that? 如何处理?

I ran into this same issue. 我遇到了同样的问题。 As a workaround, instead of using a DataTrigger you could bind the TextColor property to a Color property in your ViewModel. 解决方法是,可以使用ViewModel中的TextColor属性绑定到Color属性,而不是使用DataTrigger。 In the IsValid setter you could then set the color based on the value. 然后,可以在IsValid setter中根据该值设置颜色。

public bool IsValid
{
    get { return _isValid; }
    set
    {
        _isValid = value;
        MyNewTextColorProperty = _isValid ? Color.Blue : Color.Red;

        OnPropertyChanged();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM