2014-01-07 2 views
0

У меня есть приложение WPF в C#. Когда я запускаю приложение, он динамически создает кнопку с фоновым изображением.Как перехватить onMouseOver на кнопке

Это пример кода:

Button button = new Button(); 
button.Width = 130; 
button.Height = 190; 
ImageBrush brush = new ImageBrush(new BitmapImage(new Uri(Directory.GetCurrentDirectory()[email protected]"\Images\nao_grigio.png"))); 
brush.Stretch = Stretch.Uniform; 
buttonCoppia.Background = brush; 
button.Background = brush; 

Он работает, поэтому, когда я перехожу на кнопке с мышью изображения изменяется с помощью кнопки по умолчанию изображение.

Как я его исправил?


Я скопировал ваш код в файле XAML. Так что мой код

<Window x:Name="idWindows" x:Class="MemoryGame.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Title="MainWindow" Height="600" Width="800"> 
<Window.Resources> 
    <BitmapImage x:Key="ImageSource" UriSource="Resources\nao_grigio.png"/> 
    <BitmapImage x:Key="MouseOverImage" UriSource="Resources\nao_grigio.png"/> 
    <BitmapImage x:Key="MousePressed" UriSource="Resources\nao_grigio.png"/> 
    <Style x:Key="BtnStyle" TargetType="Button"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <Grid x:Name="Gd"> 
         <Grid.Background> 
          <ImageBrush ImageSource="{StaticResource ResourceKey= ImageSource}" Stretch="Fill"></ImageBrush> 
         </Grid.Background> 
         <ContentPresenter></ContentPresenter> 
        </Grid> 
        <ControlTemplate.Triggers> 
         <Trigger Property="Button.IsMouseOver" Value="True"> 
          <Setter Property="Background" TargetName="Gd"> 
           <Setter.Value> 
            <ImageBrush ImageSource="{StaticResource ResourceKey= MouseOverImage}" Stretch="Fill"></ImageBrush> 
           </Setter.Value> 
          </Setter> 
         </Trigger> 

        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
    <Button x:Key="MyStyle" Style="{StaticResource BtnStyle}" Height="100" Width="300"/> 
</Window.Resources> 
<Grid> 
    <Label Content="Memory" HorizontalAlignment="Left" Margin="320,10,0,0" VerticalAlignment="Top" FontSize="40"/> 
    <Label x:Name="labelTime" Content="Tempo : " HorizontalAlignment="Left" Margin="628,136,0,0" VerticalAlignment="Top" RenderTransformOrigin="0.211,-0.115"/> 
    <Label x:Name="labelSecondi" Content="0 sec" HorizontalAlignment="Right" Margin="0,136,10,0" VerticalAlignment="Top"/> 
    <Label x:Name="labelNumeroErrori" Content="Numero Errori : " HorizontalAlignment="Left" Margin="628,178,0,0" VerticalAlignment="Top"/> 
    <Label x:Name="labelNumeroErrori_Cont" Content="0" HorizontalAlignment="Right" Margin="0,178,12,0" VerticalAlignment="Top" RenderTransformOrigin="-0.125,-0.692"/> 
    <Label x:Name="labelNumeroRisposteNonDate" Content="Risposte non date : " HorizontalAlignment="Left" Margin="628,220,0,0" VerticalAlignment="Top"/> 
    <Label x:Name="labelNumeroRisposteNonDate_Cont" Content="0" HorizontalAlignment="Right" Margin="0,220,12,0" VerticalAlignment="Top" RenderTransformOrigin="-0.125,-0.692"/> 
    <Grid x:Name="gridToken" HorizontalAlignment="Left" Height="400" Margin="72,136,0,0" VerticalAlignment="Top" Width="500"/> 
</Grid> 

в MainWindow.xaml.cs у меня есть это:

Button button = new Button(); 
    ImageBrush brush = new ImageBrush(new BitmapImage(new Uri(Directory.GetCurrentDirectory()[email protected]"\Images\nao_grigio.png"))); 
    brush.Stretch = Stretch.Uniform; 
    buttonCoppia.Background = brush; 
    button.Background = brush; 
    button.Style = this.Resources["MyStyle"] as Style; 

Но это не работает.

+0

Я вижу в приложении формы C# это свойство «UseVisualStyleBackgroundColor», если это свойство UseVisualStyleBackgroundColor = false; я решил свою проблему, но в приложении WPF этого свойства нет. Как я это исправил? – bircastri

ответ

2

Вам нужно будет написать стиль для вашего контроля, чтобы он сохранял фоновое изображение в течение всего жизненного цикла (наведение мыши/выход/клик/сфокусированный/и т. Д.). Это на самом деле не очень сложно, как только вы привыкнете к нему, так что не нужно бояться :)

Эти ссылки должны получить вы охвачены в кратчайшие сроки:

How do I style Buttons

http://wpftutorial.net/Styles.html

http://msdn.microsoft.com/en-us/library/aa970773%28v=vs.110%29.aspx

0

Прочтите этот код

<BitmapImage x:Key="ImageSource" UriSource="DefaultImage.png"/> 
    <BitmapImage x:Key="MouseOverImage" UriSource="MouseOverImage.png"/> 
    <BitmapImage x:Key="MousePressed" UriSource="MousePressed.png"/> 

    <Style x:Key="BtnStyle" TargetType="Button"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <Grid x:Name="Gd"> 
         <Grid.Background> 
          <ImageBrush ImageSource="{StaticResource ResourceKey= ImageSource}" Stretch="Fill"></ImageBrush> 
         </Grid.Background> 
         <ContentPresenter></ContentPresenter> 
        </Grid> 
        <ControlTemplate.Triggers> 
         <Trigger Property="Button.IsMouseOver" Value="True"> 
          <Setter Property="Background" TargetName="Gd"> 
           <Setter.Value> 
            <ImageBrush ImageSource="{StaticResource ResourceKey= MouseOverImage}" Stretch="Fill"></ImageBrush> 
           </Setter.Value> 
          </Setter> 
         </Trigger> 
         <Trigger Property="Button.Pressed" Value="False"> 
          <Setter Property="Background" TargetName="Gd"> 
           <Setter.Value> 
            <ImageBrush ImageSource="{StaticResource ResourceKey= MousePressed}" Stretch="Fill"></ImageBrush> 
           </Setter.Value> 
          </Setter> 
         </Trigger> 
        </ControlTemplate.Triggers> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 


<Button Style="{StaticResource BtnStyle}" Height="100" Width="300"/> 
Смежные вопросы