我使用模板来更改Visual Studio中默认按钮的外观。我正在绘制一个多边形并使用ContentPresenter标签在多边形中插入文本
<ControlTemplate x:Key="AnswerChoose" TargetType="Button">
<Border BorderThickness="2">
<Grid Name="ButtonAnswer">
<Polygon Name="BorderAnswer" Points="0,50 30,20, 270,20 300,50 270,80 30,80" Stroke="White" StrokeLineJoin="Bevel" StrokeThickness="2">
<Polygon.Fill>
<LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
<GradientStop Color="#FF0A080D" Offset="0.0"/>
<GradientStop Color="#FF15224C" Offset="0.2"/>
<GradientStop Offset="0.5" Color="#FF0460C3"/>
<GradientStop Color="#FF15224C" Offset="0.8"/>
<GradientStop Color="#FF0A080D" Offset="1"/>
</LinearGradientBrush>
</Polygon.Fill>
</Polygon>
<ContentPresenter Name="ContentAnswer" VerticalAlignment="Center" HorizontalAlignment="Center"/>
</Grid>
</Border>
</ControlTemplate>
这是我的按钮:
<Grid Grid.Row="2" HorizontalAlignment="Stretch" Tap="ChangeColorButton_Tap">
<Grid VerticalAlignment="Center" HorizontalAlignment="Center">
<Grid.RowDefinitions>
<RowDefinition Height="1*"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<Button Name="A" Content="A." Grid.Column="0" Grid.Row="0" Template="{StaticResource AnswerChoose}" />
<Button Name="B" Content="B. " Grid.Column="1" Grid.Row="0" Template="{StaticResource AnswerChoose}"/>
<Button Name="C" Content="C. " Grid.Column="0" Grid.Row="1" Template="{StaticResource AnswerChoose}"/>
<Button Name="D" Content="D. " Grid.Column="1" Grid.Row="1" Template="{StaticResource AnswerChoose}"/>
</Grid>
</Grid>
现在,我想如果我点击那个按钮,它会改变颜色,但我有一个问题:如果我点击节点和边缘属性OriginalSource返回边框,如果我点击按钮的文本,它返回TextBlock。如何知道我的Visual Studio单击按钮上的任何位置是否会返回“按钮”。我在MSDN上有引用,但它只是模糊地使用OnApplyTemplate。你能告诉我如何使用它或提供其他解决方案吗?
答案 0 :(得分:0)
如果您不想为每个按钮添加事件处理程序,也许您可以尝试使用VisualTreeHelper
来搜索元素。
在ChangeColorButton_Tap
事件处理程序中尝试此代码:
var pos = e.GetPosition(null);
var buttons = VisualTreeHelper.FindElementsInHostCoordinates(pos, LayoutRoot).Where(item => item is Button);
foreach (var uiElement in buttons)
{
Debug.WriteLine(uiElement);
}