这是我最接近创建一个简单的触发器。我只想要datagrid的IsMouseOver == true来显示按钮。 问题是Setter的TargetName说:属性'TargetName'不代表'Setter'的有效目标,因为找不到名为'ButtonExpand'的元素。确保在使用目标的任何Setter,Triggers或Conditions之前声明目标。 我做错了什么?
<UserControl.Resources>
<Style TargetType="DataGrid">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ButtonExpand" Property="Visibility" Value="Visible" />
</Trigger>
</Style.Triggers>
</Style>
</UserControl.Resources>
<Grid>
<DataGrid Name="MainDataGrid" ItemsSource="{Binding Programs}" IsReadOnly="True" AutoGenerateColumns="false" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Version" Binding="{Binding Version}"/>
<DataGridTextColumn Header="Publisher" Binding="{Binding Publisher}"/>
</DataGrid.Columns>
</DataGrid>
<Button Name="ButtonExpand" Height="25" Width="25" HorizontalAlignment="Right" VerticalAlignment="Bottom" Visibility="Hidden">+</Button>
</Grid>
答案 0 :(得分:22)
TargetName不打算使用 在Triggers集合中 风格。一种风格没有 名称范围,所以它没有意义 在那里按名称引用元素。 但是一个模板(DataTemplate或 ControlTemplate)确实有 名称范围。
请参阅this链接。
您可以使用Button的DataTrigger进行相反的操作。请注意,必须在Style中设置Property Visibility才能使DataTrigger正常工作。
<Grid Name="MainGrid">
<DataGrid ItemsSource="{Binding Programs}"
IsReadOnly="True"
AutoGenerateColumns="false" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Version" Binding="{Binding Version}"/>
<DataGridTextColumn Header="Publisher" Binding="{Binding Publisher}"/>
</DataGrid.Columns>
</DataGrid>
<Button Name="ButtonExpand"
Height="25"
Width="25"
HorizontalAlignment="Right"
VerticalAlignment="Bottom"
Content="+">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MainGrid,
Path=IsMouseOver}"
Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>
另一种方法是使用转换器将ButtonExpand的Visibilty绑定到DataGrid的IsMouseOver属性。
答案 1 :(得分:0)
<Grid Name="MainGrid">
<DataGrid ItemsSource="{Binding Programs}" IsReadOnly="True" AutoGenerateColumns="false" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
<DataGridTextColumn Header="Version" Binding="{Binding Version}"/>
<DataGridTextColumn Header="Publisher" Binding="{Binding Publisher}"/>
</DataGrid.Columns>
</DataGrid>
<Button Name="ButtonExpand" Margin="0,0,20,20" Height="25" Width="25" HorizontalAlignment="Right" VerticalAlignment="Bottom" Content="+">
<Button.Style>
<Style TargetType="Button">
<Setter Property="Visibility" Value="Hidden"/>
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=MainGrid,
Path=IsMouseOver}"
Value="True">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>
</Button>
</Grid>