gpt4 book ai didi

c# - 自定义用户控件未显示在列表框中

转载 作者:太空宇宙 更新时间:2023-11-03 13:30:01 24 4
gpt4 key购买 nike

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

我的项目包括:

  • 主窗口.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>

最佳答案

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

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

为了让它工作,将构造函数中的代码更改为以下内容:

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

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

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

关于c# - 自定义用户控件未显示在列表框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20920893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com