不要“随便”用MessageBox.Show做“测试”。
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Grid x:Name="grid1">
<TextBlock Text="Hello" FontSize="20" FontWeight="Bold"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
void CustomControl1_MouseLeave(object sender, MouseEventArgs e)
{
var temp = this.Template.FindName("grid1", this) as Grid;
if (temp != null) {
temp.Background = new SolidColorBrush(Colors.Green);
}
}
void CustomControl1_MouseDown(object sender, MouseButtonEventArgs e)
{
var temp = this.Template.FindName("grid1", this) as Grid;
if (temp != null) {
temp.Background = new SolidColorBrush(Colors.Red);
}
}
<Grid>
<Border BorderBrush="Purple" BorderThickness="2" Width="100" Height="100" Background="AliceBlue">
<local:CustomControl1 HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</Grid>
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Grid x:Name="grid1">
<TextBlock Text="Hello" FontSize="20" FontWeight="Bold"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
void CustomControl1_MouseLeave(object sender, MouseEventArgs e)
{
var temp = this.Template.FindName("grid1", this) as Grid;
if (temp != null) {
temp.Background = new SolidColorBrush(Colors.Green);
}
}
void CustomControl1_MouseDown(object sender, MouseButtonEventArgs e)
{
var temp = this.Template.FindName("grid1", this) as Grid;
if (temp != null) {
temp.Background = new SolidColorBrush(Colors.Red);
}
}
<Grid>
<Border BorderBrush="Purple" BorderThickness="2" Width="100" Height="100" Background="AliceBlue">
<local:CustomControl1 HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Border>
</Grid>
我感觉是与自定义的Window有关系吧