WPF: Как связать свойство color градиентной остановки, расположенной в шаблоне controlTemplate в vb-коде?

Мне нужно сделать это для создания динамической фоновой кисти для пользовательского элемента управления (наследует ContentControl). Мой пользовательский элемент управления имеет два свойства зависимостей: StartColor и EndColor. В шаблоне элемента управления для пользовательского элемента управления элемент управления оборачивается границей, фон которой является RadialGradientBrush с градиентными остановками. Цвет одной градиентной остановки привязан к StartColor, а другой - к EndColor. У меня есть эта РАБОТА в XAML, но мне нужно преобразовать ее в код VB. Элемент border шаблона управления в XAML выполняется с помощью следующего кода:

<Style x:Key="{x:Type wpf:MyControl}" 
   TargetType="{x:Type wpf:MyControl}" 
   BasedOn="{StaticResource {x:Type ContentControl}}">
    <Style.Setters>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type wpf:MyControl}">

                      ...

                    <Border HorizontalAlignment="Stretch" 
                            x:Name="background" Width="Auto"
                            Grid.RowSpan="3" 
                            Opacity="0.9" 
                            CornerRadius="{TemplateBinding CornerRadius}">
                                <Border.Background>
                                    <Custom:RadialGradientBrush>
                                        <Custom:GradientStop Color="{Binding Path=EndColor, 
                                                            RelativeSource={RelativeSource TemplatedParent}, 
                                                            Mode=OneWay}" 
                                                            Offset="0.462"/>
                                        <Custom:GradientStop Color="{Binding StartColor, 
                                                            RelativeSource={RelativeSource TemplatedParent}, 
                                                            Mode=OneWay}" 
                                                            Offset="1"/>
                                    </Custom:RadialGradientBrush>
                                </Border.Background>
                            </Border>

                        ...

                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style.Setters>
</Style>

Я попытался создать границу в коде VB следующим образом, но это не сработало:

...
Dim backgroundBorder As New FrameworkElementFactory(GetType(Border))
        With backgroundBorder
            .Name = "background"
            .SetValue(Grid.RowSpanProperty, 3)
            .SetValue(Grid.OpacityProperty, 0.9)
            .SetBinding(Border.CornerRadiusProperty, New Binding("CornerRadius") With {.RelativeSource = New RelativeSource(RelativeSourceMode.TemplatedParent)})
        End With

        Dim backgroundBrush As New RadialGradientBrush()

        Dim startColorGradientStop As New GradientStop()
        startColorGradientStop.Offset = 1.0
        BindingOperations.SetBinding(startColorGradientStop, GradientStop.ColorProperty, New Binding("StartColor") With {.RelativeSource = New RelativeSource(RelativeSourceMode.TemplatedParent), .Mode = BindingMode.OneWay})
        backgroundBrush.GradientStops.Add(startColorGradientStop)

        Dim endColorGradientStop As New GradientStop()
        endColorGradientStop.Offset = 0.462
        BindingOperations.SetBinding(endColorGradientStop, GradientStop.ColorProperty, New Binding("EndColor") With {.RelativeSource = New RelativeSource(RelativeSourceMode.TemplatedParent), .Mode = BindingMode.OneWay})
        backgroundBrush.GradientStops.Add(endColorGradientStop)

backgroundBorder.SetValue(Border.BackgroundProperty, backgroundBrush)
...



Любые идеи о том, как я могу сделать это в коде VB?

2 ответа

Решение

Знаете ли вы, что подход FrameworkElementFactory больше не рекомендуется, согласно MS? Рекомендуемый подход заключается в создании любого элемента / ресурса в коде с помощью XamlReader.Parse.

Вы должны получить доступ к Родительскому Контент-Контролю, для которого Граница должна быть Контентом. И установите это в своем коде VB.

Под ContentControl я имел в виду, какой бы элемент управления не являлся родительским для Border, вам нужно получить к нему доступ через функцию переопределения OnApplyTemplate и добавить созданную VB.NET рамку в качестве дочернего элемента для этого визуала.

Другие вопросы по тегам