在WPF Code Behind中将现有控件模板设置为Content Property

时间:2015-01-30 08:31:25

标签: c# wpf binding controltemplate

我有一个非常简单的XAML                                            能见度="折叠" X1 =" 1"保证金=" -35 0 0 0" Y1 =" 0.4">                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

                        <Label.Content>
                            <Slider Grid.Column="0"
                                    Width="20"
                                    Height="65"
                                     IsDirectionReversed="True"
                                    Maximum="0.1"
                                    Minimum="-4"
                                    Orientation="Vertical"                                                                                
                                    x:Name="Slider1" 
                                    Value="{Binding  Source={x:Reference scaleFactorModifier},
                                                                Path=ZoomScaleFactor, Mode=TwoWay}" />
                        </Label.Content>
                    </Label>
                </SciChart:CustomAnnotation.Content>

            </SciChart:CustomAnnotation>

现在由于某种原因,我需要从后面的代码设置CustomControl.Content属性。是否有可能将所有标签控件移动到某个样式和模板,并在运行时使用该特定样式或模板设置CustomControl内容属性。

更新

使用代码的原因

实际上我的控件中有Annotations属性,可以根据需要对其进行任何控制。以前我在我的控件中使用了硬编码注释并手动放置了控件。现在我想绑定Annotations属性。我可以创建这种类型的属性并在其中添加CustomAnnotation对象。但是customAnnotation对象需要在其中包含标签和其他控件,我该怎么做?

2 个答案:

答案 0 :(得分:1)

如果我已正确理解您的问题,我相信您可以使用DataTemplateContentControl来执行您想要的操作。首先,在DataTemplate中定义Label

<DataTemplate DataType="{x:Type YourPrefix:YourDataType}">
    <!-- define your Label here -->
</DataTemplate>

然后,您可以将Content的{​​{1}}属性设置为CustomControl,将ContentControl属性设置为{{1}对象的实例}}:

Content

我知道您希望以编程方式执行此操作,但这很容易解决:

YourDataType

我想知道你是否真的需要使用你的<ContentControl Content="{Binding InstanceOfYourDataType}" /> ,但我会把它留给你。

答案 1 :(得分:0)

我从该xaml创建一个用户控件,然后将CustomControl.Content设置为用户控件的新实例。这可能不是最好的解决方案,但这就是我现在所拥有的一切。