如何在WPF运行时期间在控件周围设置边框?

时间:2009-12-27 02:54:55

标签: c# wpf runtime border

我的WPF表单上有一个Image控件。如何在运行期间围绕它创建边框?

这是我的XAML代码:

<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" />

另外,我想知道如何删除边框。

如果我更好地陈述我的问题,可能会有更好的解决方案。

我有很多图像,当用户说:“嘿,只要告诉我所有照片中的女人。”我想要一种方法来突出或吸引用户注意我需要他们看到的任何图像。我正在考虑添加边框,但也许这对于可以更容易解决的问题来说太过分了。

任何帮助?

3 个答案:

答案 0 :(得分:1)

没有直接的方法,因为Border是一个容器,所以您必须从其父级中删除Image,而是放置Border,然后放置Image回到Border ...

另一种选择是使用模板:

<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"/>

如果要在图像周围放置边框,只需将模板指定给图像:

image1.Template = this.FindResource("imageWithBorder") as ControlTemplate;

答案 1 :(得分:1)

虽然它在视觉上与边框非常不同,但您可以使用外部发光来表示图像的重要性。然后,您不必更改图像的父级。

或者,您可以使用自定义Adorner在图像周围放置边框。关于adorners的好消息可以在msdn上找到。

答案 2 :(得分:1)

根据您所说的需求,我建议您使用带有自定义ItemContainerStyle的ListBox - 一个始终具有边框但只有在选中该项时才能看到它的那个。

这是基本想法:

<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>
相关问题