绑定应用了样式/模板的控件

3
我想(重新)对一个控件进行模板化,比如ComboBox。
XAML:
<ComboBox Style="{StaticResource MyComboBoxStyle}" ... >
    <!-- ... -->
</ComboBox>

在ControlTemplate中,我想要一个按钮。
资源字典:
<Style x:Key="MyComboBoxStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Grid>
                    <!-- ... -->

                    <Button Command="{TemplateBinding Tag}" CommandParameter="{Binding ???}" />

                    <!-- ... -->
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

但我想将CommandParameter设置为应用模板的控件(在此示例中为ComboBox)。
我该如何解决这个问题?
1个回答

10

好的,我找到了正确的解决方案。

我将绑定设置为 Binding RelativeSource={RelativeSource TemplatedParent}

<Style x:Key="MyComboBoxStyle" TargetType="{x:Type ComboBox}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Grid>
                    <!-- ... -->

                    <Button Command="{TemplateBinding Tag}" CommandParameter="{Binding RelativeSource={RelativeSource TemplatedParent}}" />

                    <!-- ... -->
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接