我有一個PCL,我正在使用MVVM模式。 我正在構建一個togglebutton,它在viewmodel中的相關屬性被激活時觸發,具有行爲和觸發器。 這是我的行爲Xamarin形式ToggleButton
public class ToggleBehavior : Behavior<View>
{
TapGestureRecognizer tapRecognizer;
public static readonly BindableProperty IsToggledProperty = BindableProperty.Create<ToggleBehavior, bool>(tb => tb.IsToggled, false);
public bool IsToggled
{
set { SetValue(IsToggledProperty, value); }
get { return (bool)GetValue(IsToggledProperty); }
}
}
這是我如何消費自己的行爲
<Button Text="AUTO" Style="{StaticResource SmallEllipseButton}" BackgroundColor="{StaticResource BackgroundColor}" cm:Message.Attach="Automatic($dataContext)">
<Button.Behaviors>
<local:ToggleBehavior x:Name="autoToggleBehavior" IsToggled="{Binding CurrentMode,Converter={StaticResource modeToBooleanConverter}, ConverterParameter=AUTO}"/>
</Button.Behaviors>
<Button.Triggers>
<DataTrigger TargetType="Button" Binding="{Binding Source={x:Reference autoToggleBehavior},Path=IsToggled}" Value="False" >
<Setter Property="BackgroundColor" Value="White"/>
<Setter Property="BorderColor" Value="White"/>
<Setter Property="TextColor" Value="Gray"/>
</DataTrigger>
<DataTrigger TargetType="Button" Binding="{Binding Source={x:Reference autoToggleBehavior},Path=IsToggled}" Value="True" >
<Setter Property="BackgroundColor" Value="{StaticResource BackgroundColor}"/>
<Setter Property="TextColor" Value="White"/>
</DataTrigger>
</Button.Triggers>
</Button>
的問題是,物業IsToggled未正確在此IsToggled="{Binding CurrentMode,Converter={StaticResource modeToBooleanConverter}, ConverterParameter=AUTO}"/>
如果我將它設置靜態爲true或false綁定有用。 我認爲的問題是,我無法將這個屬性用dinamically綁定。 我在同一頁面使用與同一個轉換器的IsVisible屬性相同的綁定,並且它可以工作。 如果我在轉換器中放置一個斷點,應用程序不會中斷它,但IsVisible屬性會中斷。
結合還不能正常工作。它只有在我將其設置爲true/false時纔有效,但似乎我無法將其綁定到視圖模型屬性 – Marco24690
上面的代碼確實對我有用。訣竅是從可綁定對象設置OnAttachedTo(BindableObject)上的綁定上下文。這對我來說似乎是一種破綻,但我懷疑行爲不是被設計成可綁定的,或者是XF代碼中存在一個錯誤。您可能想在Bugzilla中創建一個錯誤報告。 – SKall
我沒有添加OnAttachedTo方法。現在它也適用於Button。謝謝 – Marco24690