代码之家  ›  专栏  ›  技术社区  ›  Sergio Tapia

在WPF中,如何在运行时围绕控件设置边框?

  •  0
  • Sergio Tapia  · 技术社区  · 15 年前

    我的WPF窗体上有一个图像控件。如何在运行时围绕它创建边界?

    这是我的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 回复  |  直到 15 年前
        1
  •  1
  •   dustyburwell    15 年前

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

    或者,可以使用自定义装饰器在图像周围放置边框。可以在msdn上找到有关装饰器的详细信息。

        2
  •  1
  •   Thomas Levesque    15 年前

    没有直接的方法,因为 Border 是一个容器,因此您必须移除 Image 从它的父母那里,把 边界 相反,把 图像 回到 边界

    另一种选择是使用模板:

    <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;
    
        3
  •  1
  •   Ray Burns    15 年前

    为了满足您的需求,我建议您使用一个带有自定义项容器样式的列表框-该列表框始终具有边框,但只有在选中该项时才使其可见。

    基本思路如下:

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