views:

87

answers:

3

I have an Image control on my WPF Form. How can I create a border around it during runtime?

Here's my XAML code:

<Image Margin="2.5" 
       Grid.Column="1" Grid.Row="0" 
       x:Name="Behemoth" Source="Images/Hero/Behemoth.gif" Stretch="Fill"     
       MouseEnter="HeroMouseEnter" 
       MouseLeave="HeroMouseLeave" 
       MouseDown="HeroMouseClick" />

Also, I want to know how to remove the border.

Maybe if I state my problem better there is an even better solution available.

I have many Images, and when a user says: "Hey, just show me the woman out of all the picture." I want a way to sort of highlight or draw the users attention to whatever images I need them to see. I was thinking about adding a border, but maybe that's too much work for something that can be solved easier.

Any help?

A: 

There's no straightforward way to do it, because the Border is a container, so you would have to remove the Image from its parent, put the Border instead, and put the Image back in the Border...

Another option would be to use templates :

<Window.Resources>
    <ControlTemplate x:Key="imageWithBorder" TargetType="{x:Type Image}">
        <Border BorderBrush="Red" BorderThickness="2">
            <Image Source="{TemplateBinding Source}" />
        </Border>
    </ControlTemplate>
</Window.Resources>

...

   <Image Name="image1" Source="foo.png"/>

When you want to put the border around the image, just assign the template to the image :

image1.Template = this.FindResource("imageWithBorder") as ControlTemplate;
Thomas Levesque
+1  A: 

Although it's visually very different from a border, you could use an outter glow to signify the importance of the image. Then, you don't have to change the parent of the image.

Alternatively, you could use a custom Adorner to place a border around the image. Good info on Adorners can be found on msdn.

dustyburwell
A: 

For your stated needs, I suggest you use a ListBox with a custom ItemContainerStyle - one that always has a border but only makes it visible if the item is selected.

Here's the basic idea:

<ListBox ItemsSource="{Binding MyImageObjects}">
  <ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type ListBoxItem}">
            <Border x:Name="border">
              <ContentPresenter />
            </Border>
            <ControlTemplate.Triggers>
              <Trigger Property="ListBoxItem.IsSelected" Value="True">
                <Setter ElementName="border" Property="BorderBrush" Value="Blue" />
                <Setter ElementName="border" Property="BorderThickness" Value="2" />
              </Trigger>
            </ControlTemplate.Triggers>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </ListBox.ItemContainerStyle>
</ListBox>
Ray Burns