启用了基于父命令的WPF样式子控件
本文关键字:WPF 样式 控件 命令 于父 启用 | 更新日期: 2023-09-27 18:06:41
我只是想让我的Button
模板中的Label
看起来禁用。搜索了一下互联网,这似乎是一个简单的任务,我做错了什么?
<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>
用ElementName
代替。RelativeSource = FindAncestor
不会在这里工作,因为按钮不在于视觉树,而是StackPanel的兄弟姐妹。给name to button
并使用它在你的绑定使用ElementName
-
<Button Command="{Binding CommandProcess}" x:Name="MyButton">
and in datattrigger -
<DataTrigger Binding="{Binding Path=IsEnabled, ElementName=MyButton}"
Value="False">
.....
</DataTrigger>
标签和按钮的Visual Tree
结构如下-
Label <--- StackPanel <--- StackPanel's Parent
Button <--- StackPanel's Parent
可以看到,按钮是StackPanel的兄弟,它位于标签的可视树中,这就是为什么FindAncestor
不会让你到Button
。