WPF基于启用父命令的样式子控件

时间:2013-03-30 15:56:17

标签: c# wpf button styles label

我只想让我的Label模板中的Button看起来已禁用。搜索互联网,这似乎是一个简单的任务,我做错了什么?

<Button Command="{Binding CommandProcess}">
    <StackPanel Orientation="Horizontal">
        <Image Source="Images\Cloud-Upload.png"/>

        <Label Content="Upload and Process" Foreground="White" VerticalAlignment="Center" FontWeight="Bold" FontSize="18.667" Margin="5,0,0,0">
            <Label.Style>
                <Style TargetType="Label">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsEnabled, RelativeSource={RelativeSource AncestorType={x:Type Button}}}" Value="False">
                            <Setter Property="Foreground" Value="Gray"></Setter>
                            <Setter Property="ToolTip" Value="Please select a record type for each file selected for processing"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Label.Style>
        </Label>
    </StackPanel>
</Button>

EDIT:(使用RV1987 的答案后完整代码)

<Button Command="{Binding CommandProcess}" x:Name="ProcessButton">
    <StackPanel Orientation="Horizontal">
        <Image Source="Images\Cloud-Upload.png"/>

        <Label Content="Upload and Process" VerticalAlignment="Center" FontWeight="Bold" FontSize="18.667" Margin="5,0,0,0">
            <Label.Style>
                <Style TargetType="Label">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=IsEnabled, ElementName=ProcessButton}" Value="True">
                            <Setter Property="Foreground" Value="White"></Setter>
                        </DataTrigger>

                        <DataTrigger Binding="{Binding Path=IsEnabled, ElementName=ProcessButton}" Value="False">
                            <Setter Property="Foreground" Value="Gray"></Setter>
                            <Setter Property="ToolTip" Value="Please select a record type for each file selected for processing"></Setter>
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Label.Style>
        </Label>
    </StackPanel>
</Button>

1 个答案:

答案 0 :(得分:1)

请改用ElementNameRelativeSource = FindAncestor在这里不起作用,因为按钮不在Visual Tree中,而是它的StackPanel的兄弟。授予name to button并使用ElementName -

在绑定中使用它
<Button Command="{Binding CommandProcess}" x:Name="MyButton">

并在DataTrigger中 -

<DataTrigger Binding="{Binding Path=IsEnabled, ElementName=MyButton}"
             Value="False">
   .....
</DataTrigger>
Label和Button的

Visual Tree结构就像这样 -

Label <--- StackPanel <--- StackPanel's Parent
Button <--- StackPanel's Parent

可以看出Button是StackPanel的兄弟,它现在位于Label的Visual树中,这就是为什么FindAncestor无法让你进入Button