使用TemplateBinding

时间:2018-03-29 14:15:16

标签: wpf xaml

我试图实现一个简单的组合框(绑定到字符串列表),将左边的每个项目显示为右侧的字符串标签和图标(以GeometryDrawing的形式)。我希望包装盒中的物品能够继承我使用的颜色,因为我有自定义方案(背景为深色和白色)。

我能够使用TemplateBinding(绑定到ComboBoxItem.Foreground)来使文本标签的颜色正确显示但是我无法对几何图形执行相同的操作,我无法弄清楚原因。

这是我 尝试 实现的图片。

Icon shows up

请注意,图标左侧显示的图标很清楚。这只有在我明确指定" White"作为GeometryDrawing的画笔。

以下是我正在使用的XAML。

<tk:RadComboBox ItemsSource="{Binding PostAnalysisRoutines}"
                Grid.Row="8" Grid.Column="2"
                Text="{Binding Settings.PostCaptureAnalysisRoutine, Mode=TwoWay}">

    <!-- 
    Each item in the box is a horizontal stackpanel with an icon for 
    the routine on the left and the routine name on the right
    -->

    <tk:RadComboBox.ItemTemplate>
        <DataTemplate DataType="sdk:AnalysisRoutine">
            <StackPanel Orientation="Horizontal">

                <Image Width="30" Height="30">
                    <Image.Source>
                        <DrawingImage>
                            <DrawingImage.Drawing>
                                <!-- ***FORCE TO USE "White" here WHY???*** -->
                                <GeometryDrawing Brush="White"
                                                 Geometry="{Binding Converter={StaticResource PathGeometryConverter}}"
                                />
                            </DrawingImage.Drawing>
                        </DrawingImage>
                    </Image.Source>
                </Image>
                <!-- *** BUT ITS OK TO USE TemplateBinding HERE.  WHY??? *** -->
                <Label Foreground="{TemplateBinding tk:RadComboBoxItem.Foreground}"
                       Background="{TemplateBinding tk:RadComboBoxItem.Background}"
                       Content="{Binding}"/>
            </StackPanel>
        </DataTemplate>
    </tk:RadComboBox.ItemTemplate>

</tk:RadComboBox>

几点说明:

  • 我在这里使用Telerik的RadComboBox,但如果我将其切换到普通的WPF ComboBox,我会发现类似的问题。
  • 我可以使用TemplateBindings将Label的前景色和背景色绑定到ComboBoxItem。那些工作正常。
  • PathGeometryConverter只获取字符串名称并为其找到预定义的PathGeometry资源。

不幸的是,我无法将相同的TemplateBinding用于GeometryDrawing&#34;刷&#34;属性。当我尝试......

<GeometryDrawing Brush="{TemplateBinding tk:RadComboBoxItem.Foreground}"
                 Geometry="{Binding Converter={StaticResource PathGeometryConverter}}"
/>

我最终得到了这个:

Icon invisible

因此,我被迫明确指定&#34; White&#34;作为画笔的颜色    几何绘图使这项工作。

在我的模板中制作GeometryDrawing的正确方法是什么?#34;继承&#34;周围的配色方案......?是否有某种我缺少的TemplateBinding?

1 个答案:

答案 0 :(得分:1)

我认为你的问题是因为你正在使用模板绑定与资源中出现的东西相结合,或者因为它是模仿的东西的几个级别。如果几何体直接在模板中,那么我认为它可以工作。

我建议您尝试使用relativesource和ancestortype tk进行绑定:RadComboBoxItem,path = foreground。 或者来源templatedparent。

我也会使用路径而不是图像。在这种情况下,它可能会产生很小的差异,但路径可能更清晰。您可以将路径的数据绑定到Geometry资源。或者至少我认为你可以,我通常直接将它们设置为动态或静态资源。