Wpf 从控件外部绑定到ControlTemplate元素

Wpf 从控件外部绑定到ControlTemplate元素,wpf,wpf-controls,Wpf,Wpf Controls,在我的WPF窗口中,我需要绑定到ControlTemplate内部的值 以下是我的代码(最大简化): 但是它不起作用…我想你不能用那种方式绑定。您可以做的是拥有一个公共资源,它同时提供给border和rectangle。请参阅下面的代码 <Window.Resources> <SolidColorBrush x:Key="SameKey" Color="Green"/> <Style TargetType="Butt

在我的WPF窗口中,我需要绑定到ControlTemplate内部的值

以下是我的代码(最大简化):


但是它不起作用…

我想你不能用那种方式绑定。您可以做的是拥有一个公共资源,它同时提供给border和rectangle。请参阅下面的代码

 <Window.Resources>
    <SolidColorBrush x:Key="SameKey" 
               Color="Green"/>
    <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="MyBorder" Height="100" Width="100" Background="{StaticResource SameKey}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel>
        <Button Name="MyButtonInstance" />
        <Rectangle Name="MyRectangle" Width="100" Height="200" 
             Fill="{StaticResource SameKey}" />
    </StackPanel>
</Grid>


问题在于,在我的实际案例中,ControlTemplate属性可能会在运行时更改(它实际上是ActualHeight属性)。。。我不能使用静态值。请尝试使用DynamicResource@dzb这没有多大意义,因为模板化按钮可能有多个实例,即多个边框。您将绑定到哪个Border实例的实际高度?@Clemens在我的例子中,只有一个控件使用ControlTemplate。有没有办法从模板元素中获取属性值?为什么不使用按钮的实际宽度?应与其模板内边框的值相同。
Fill="{Binding ElementName=MyBorder, Path=Background}"
 <Window.Resources>
    <SolidColorBrush x:Key="SameKey" 
               Color="Green"/>
    <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="MyBorder" Height="100" Width="100" Background="{StaticResource SameKey}" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <StackPanel>
        <Button Name="MyButtonInstance" />
        <Rectangle Name="MyRectangle" Width="100" Height="200" 
             Fill="{StaticResource SameKey}" />
    </StackPanel>
</Grid>