如何从代码后面更改资源中的矢量颜色

时间:2018-06-04 19:43:59

标签: wpf vector

如何从后面的代码中更改矢量颜色?此示例中的代码不起作用。

来自资源词典..

<VisualBrush x:Key="Alarm-Light">
    <VisualBrush.Visual>
        <Canvas>
            <Path  Data="M12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22M12,7L7,12H10V16H14V12H17L12,7Z" Fill="#424242" />
        </Canvas>
    </VisualBrush.Visual>
</VisualBrush>

来自Xaml ..

<TextBlock x:Name="TextConnect" Width="20">
<Rectangle x:Name="AlarmLight" Fill="{StaticResource Alarm-Light}" Height="16" Width="16" />

背后的代码......

 private void Connection_Check()
 {
        var brush = LocalSystem.Connected ? new SolidColorBrush(Colors.GreenYellow) : new SolidColorBrush(Colors.DimGray);
        AlarmLight.Fill = brush;
 }

1 个答案:

答案 0 :(得分:1)

这有效:

    <VisualBrush x:Key="Alarm-Light">
        <VisualBrush.Visual>
            <Canvas>
                <Path Fill="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=AlarmFill}" Data="M12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22M12,7L7,12H10V16H14V12H17L12,7Z"  />
            </Canvas>
        </VisualBrush.Visual>
    </VisualBrush>

使用此代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        AlarmFill = new SolidColorBrush(Colors.Blue);
    }

    /// <summary>
    /// Gets or Sets AlarmFill Dependency Property
    /// </summary>
    public Brush AlarmFill
    {
        get { return (Brush)GetValue(AlarmFillProperty); }
        set { SetValue(AlarmFillProperty, value); }
    }
    public static readonly DependencyProperty AlarmFillProperty =
        DependencyProperty.Register("AlarmFill", typeof(Brush), typeof(MainWindow), new PropertyMetadata(null));

}

或者这个:

    <VisualBrush x:Key="Alarm-Light">
        <VisualBrush.Visual>
            <Canvas>
                <Path Fill="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=DataContext.AlarmFill}" Data="M12,22A10,10 0 0,1 2,12A10,10 0 0,1 12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22M12,7L7,12H10V16H14V12H17L12,7Z"  />
            </Canvas>
        </VisualBrush.Visual>
    </VisualBrush>

使用此代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        AlarmFill = new SolidColorBrush(Colors.Blue);
    }

    /// <summary>
    /// Gets or Sets AlarmFill Dependency Property
    /// </summary>
    public Brush AlarmFill
    {
        get { return (Brush)GetValue(AlarmFillProperty); }
        set { SetValue(AlarmFillProperty, value); }
    }
    public static readonly DependencyProperty AlarmFillProperty =
        DependencyProperty.Register("AlarmFill", typeof(Brush), typeof(MainWindow), new PropertyMetadata(null));

}