自定义UserControl未显示在ListBox中

时间:2014-01-04 12:22:05

标签: c# wpf listbox controls listboxitem

我在以UserControls编程方式显示自定义ListBox时遇到问题。我似乎无法弄清楚出了什么问题。列表项显示没有图像或文本。

我的项目包括:

  • MainWindow.xaml
  • MainWindow.xaml.cs
  • cvMenuItem.xaml
  • cvMenuItem.xaml.cs

MainWindow.xaml.cs代码

private void cvMenuItem_MouseLeftButtonUp_1(object sender, MouseButtonEventArgs e)
{
    lstContacts.Items.Clear();

    cvMenuItem test = new cvMenuItem("test", 
        Environment.GetEnvironmentVariable("USERPROFILE") + @"\Downloads\images.jpg");

    lstContacts.Items.Add(test);
}

cvMenuItem.xaml.cs代码

public partial class cvMenuItem : UserControl
{
    public cvMenuItem()
    {
        InitializeComponent();
    }

    public cvMenuItem(string text, string Logo)
    {
        this.Height = 50;
        this.Width = 186;
        txtService = new TextBlock() { Width = 100, Height = 50 };
        imgLogo = new Image() { Width = 50, Height = 50 };

        //Just found out, adding the objects as childeren partially works
        this.AddChild(imgLogo);
        //But I can't add txtService as Childeren
        //this.AddChild(txtService);

        this.Services = text;
        this.Logo = Logo;
    }

    public string Services
    {
        get{ return txtService.Text.ToString() }
        set
        {
            txtService.Text = value;
        }
    }

    public string Logo
    {
        get{ return imgLogo.Source.ToString(); }
        set
        {
            var uriSource = new Uri(value);
            imgLogo.Source = new BitmapImage(uriSource);
        }
    }

我的cvMenuItem.xaml.cs

<UserControl x:Class="WpfApplication1.cvMenuItem"
             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" 
             mc:Ignorable="d"  Height="50" Width="186">
    <Grid Width="186" VerticalAlignment="Top">
        <Image Name="imgLogo" Height="50" Width="50" HorizontalAlignment="Left" VerticalAlignment="Top" OpacityMask="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}" />
        <TextBlock Name="txtService" HorizontalAlignment="Left" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Bottom" Height="18" Width="121" Margin="70,0,0,18" RenderTransformOrigin="0.499,1.932"/>
    </Grid>
</UserControl>

1 个答案:

答案 0 :(得分:1)

首先,您需要在已添加的自定义构造函数中调用InitializeComponent,因为需要正确处理XAML。否则,在运行应用程序时,您在XAML中添加的所有控件都将为null。

此外,在代码隐藏中再次创建TextBlockImage毫无意义。您只需使用在XAML中创建的那些。

为了使其正常工作,请将构造函数中的代码更改为以下内容:

public cvMenuItem(string text, string Logo)
{
    InitializeComponent();

    this.Height = 50;
    this.Width = 186;

    this.Services = text;
    this.Logo = Logo;
}