2015-05-08 121 views
0

我想在我的控件Xamarin.Forms上設置DataTrigger,但我無法讓它工作。Xamarin.Forms DataTrigger不工作

我有房產的視圖模型與OnPropertyChange執行的bool IsValid

我曾嘗試:

DataTrigger在XAML:

<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> 

獲取例外:The Property TargetType is required to create a Xamarin.Forms.DataTrigger object.

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 has been thrown by the target of an invocation.

我已經試過也在改變行:this.Style.Triggers.Add(_item);this.Triggers.Add(_item);。這並沒有引發異常,但它沒有奏效。

在這最後的嘗試,它甚至擊中轉換器,但不會改變控件的TextColor。

我做錯了什麼?如何處理?

+0

我想你可能會打一個(已知)的問題:http://forums.xamarin.com/discussion/30465/using-datatrigger-in-xaml – Krumelur

+1

那麼有沒有其他的方法來處理這個問題?它是最重要的功能之一:( – Tomasz

回答

-1

我遇到了同樣的問題。作爲一種解決方法,您可以將TextColor屬性綁定到ViewModel中的Color屬性,而不是使用DataTrigger。在IsValid設置器中,您可以根據該值設置顏色。

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

     OnPropertyChanged(); 
    } 
} 
+2

這不是一個可接受的解決方案,ViewModel不應該知道任何有關頁面樣式。 –