我想在特定条件下使用“按钮触发器”更改线条颜色

时间:2019-05-20 05:22:53

标签: c# xaml

我要更改line1和line2的颜色,如下所示。 如何在C#代码中绑定变量? 有解决下面代码的好方法吗?

  • xaml代码
FCMPlugin.onNotification(function(data){
    if(data.wasTapped){
      //Notification was received on device tray and tapped by the user.
      alert( JSON.stringify(data) );
    }else{
      //Notification was received in foreground. Maybe the user needs to be notified.
      alert( JSON.stringify(data) );
    }
});
  • c#代码
<ControlTemplate TargetType="ToggleButton">
    <Grid>
        <Grid Width="6" Height="6" HorizontalAlignment="Right" Margin="0,0,14,0">
            <Line x:Name="line1" X1="0" Y1="0" X2="6" Y2="6" Stroke="#BDC4CF" StrokeThickness="1"/>
            <Line x:Name="line2" X1="0" Y1="6" X2="6" Y2="0" Stroke="#BDC4CF" StrokeThickness="1"/>
        </Grid>
    </Grid>

    <ControlTemplate.Triggers>
        <Trigger Property="IsChecked" Value="True">
            <Setter TargetName="line1" Property="Stroke" Value="{binding linecolor}"/>
            <Setter TargetName="line2" Property="Stroke" Value="{binding linecolor}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

1 个答案:

答案 0 :(得分:0)

我认为您需要在这里重新考虑您的方法。 首先,有一些未知的东西。 我只会假设您的isPicked布尔值是一个属性。

我要使用的方法是使用ValueConverter

因此,首先在您的视图DataContext中,我将拥有IsPicked属性:

private bool isPicked;
public bool IsPicked
{
    get { return isPicked; }
    set { isPicked = value; OnPropertyChanged(); }
}

然后我将为转换器创建一个新的.cs文件:

class BoolToColor : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? "#3EF79B" : "#FFFFFF";
        /*Same as:
        if((bool)value) 
        {
            return "#3EF79B";
        } 
        else 
        {
            return "#FFFFFF";
        }*/
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

然后最后将其全部设置在视图中(在这种情况下,我使用了Window):

<Window.Resources>
    <local:BoolToColor x:Key="BoolToColor" />
</Window.Resources>
<Grid>
    <Button Width="50" Height="50" Click="Button_Click" />
    <Grid Width="20" Height="20" HorizontalAlignment="Right" Margin="0,0,14,0">
        <Line x:Name="line1" X1="0" Y1="0" X2="20" Y2="20" Stroke="{Binding IsPicked, Converter={StaticResource BoolToColor}}" StrokeThickness="1"/>
        <Line x:Name="line2" X1="0" Y1="20" X2="20" Y2="0" Stroke="{Binding IsPicked, Converter={StaticResource BoolToColor}}" StrokeThickness="1"/>
    </Grid>
</Grid>

但是等一下有按钮吗?是的,我添加了一个按钮来测试颜色变化。 这是Button_Click的代码:

private void Button_Click(object sender, RoutedEventArgs e)
{
    IsPicked = !IsPicked;
}

最后,我希望您能想到可以代替按钮来更改IsPicked的属性值以设置颜色。我希望这可以帮助您继续进行您的项目:)