WPF,如何将值设置为绑定在相同元素值的触发器中

时间:2013-02-01 11:20:12

标签: wpf

如何将Image的值绑定到Image2值?

<Style x:Key="ImageButton" TargetType="c:ImageButton">
       <Setter Property="Image" Value="/*My image 1*/" />
       <Setter Property="Image2" Value="/*My image 2*/" />
       <Setter Property="Template">
          <Setter.Value>
             <ControlTemplate TargetType="c:ImageButton">
                   <StackPanel Orientation="Horizontal" Height="30" Width="30">
                       <Image Width="30" Height="30" Source="{TemplateBinding Image}" />
                    </StackPanel>
             </ControlTemplate>
          </Setter.Value>
       </Setter>
        <Style.Triggers>
           <Trigger Property="IsMouseOver" Value="True">
               <Setter Property="Image" Value="{Binding to Property Image2 value}" /> // How bind value to Image2
           </Trigger>
       </Style.Triggers>

</Style>

3 个答案:

答案 0 :(得分:8)

由于Image2ImageButton上的属性,因此您只需使用ImageButton将绑定源设置为RelativeSource Self控件,然后绑定到Image2即可1}}属性

<Setter Property="Image" 
        Value="{Binding Image2, RelativeSource={RelativeSource Self}}" />

答案 1 :(得分:0)

您可以尝试使用Image1

访问ElementName
{Binding ElementName=Image1, Path=DataContext}

确保将Image1定义为

<Image Name="Image1" Width="30" Height="30" Source="{TemplateBinding Image}" />

答案 2 :(得分:0)

我不确定它是否适用于您的情况,但您可以尝试以下代码:

<Style x:Key="ImageButton" TargetType="c:ImageButton">
    <Setter Property="Image" Value="/*My image 1*/" />
    <Setter Property="Image2" Value="/*My image 2*/" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="c:ImageButton">
                <StackPanel Orientation="Horizontal" Height="30" Width="30">
                    <Image x:Name="MyImage" Width="30" Height="30" Source="{TemplateBinding Image}" />
                </StackPanel>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="MyImage" Property="Source" Value="{TemplateBinding Image2}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>                
        </Setter.Value>
    </Setter>
</Style>