【问题标题】:Set an existing control template as Content Property in WPF Code Behind在 WPF 代码后面将现有控件模板设置为内容属性
【发布时间】:2015-02-02 04:37:03
【问题描述】:

我有一个非常简单的 XAML Visibility="Collapsed" X1="1" Margin="-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 内容属性。

更新

使用 Code behind 的原因

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

【问题讨论】:

  • 可能是XY problem。为什么要从代码隐藏中设置一些东西?
  • @dymanoid 嗨,我明白你的意思并更新我的问题并提到 X 而不是问 Y。请看一下。

标签: c# wpf binding controltemplate


【解决方案1】:

如果我正确理解了您的问题,我相信您可以使用DataTemplateContentControl 做您想做的事。首先,用你的Label 定义一个DataTemplate

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

然后您可以将CustomControlContent 属性设置为ContentControl,该ContentControl 将其自己的Content 属性设置为YourDataType 类型对象的实例:

<ContentControl Content="{Binding InstanceOfYourDataType}" />

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

ContentControl contentControl = new ContentControl();
contentControl.Content = instanceOfYourDataType;
yourCustomControl.Content = contentControl;

我想知道你是否真的需要使用你的CustomControl,但我会留给你。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-21
      • 2019-02-05
      • 2011-03-23
      相关资源
      最近更新 更多