WPF:自定义控件

时间:2019-05-17 05:30:00

标签: c# .net wpf

我有一个奇怪的问题,我不知道该怎么找到-我在这里寻找了类似的帖子,但是失败了。

问题是我在WPF中具有自定义控件,显然,我想在多个项目中重用它。

该控件中有图片背景,上面有标签(用Panel.ZIndex确保)。

在一个项目中它可以正确显示,而在另一个项目中,Label仅显示,由于某种原因图像没有显示。

可能是什么问题?我对此感到迷茫...

下面的控件代码:

<UserControl x:Class="SampleControls.LabelWithBoxBackground"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:SampleControls"
             mc:Ignorable="d" 
             d:DesignHeight="150" d:DesignWidth="400" x:Name="labelWithBoxBackground">
    <Grid>
        <Image Source="pack://application:,,,/Images/boxImage.png" Stretch="Fill" Panel.ZIndex="1"/>
        <TextBlock Background="White" Text="{Binding ElementName=labelWithBoxBackground, Path=Text}" Margin="0,20,0,0" Panel.ZIndex="2" HorizontalAlignment="Center" VerticalAlignment="Center" FontWeight="Bold" FontFamily="Calibri"/>
    </Grid>
</UserControl>

后面的代码:

public partial class LabelWithBoxBackground : UserControl
{
  public static readonly DependencyProperty TextProperty =
    DependencyProperty.Register("Text", typeof(string), typeof(LabelWithBoxBackground), new FrameworkPropertyMetadata(string.Empty));

  public string Text
  {
    get { return GetValue(TextProperty).ToString(); }
    set { SetValue(TextProperty, value); }
  }

  public LabelWithBoxBackground()
  {
    InitializeComponent();
  }
}

1 个答案:

答案 0 :(得分:1)

使用完整的Resource File Pack URI,包括UserControl库的程序集名称(而不是名称空间):

Source="pack://application:,,,/SampleControls;component/Images/boxImage.png"

还要确保将图像文件的“生成操作”设置为“资源”。


请注意,此处设置Panel.ZIndex是没有意义的。默认情况下,元素按照在XAML中声明的顺序堆叠,因此,即使不设置ZIndex,TextBlock也始终位于Image的顶部。

相关问题