【问题标题】:c# listBox with various elements binded to a list of stringsc# listBox,各种元素绑定到字符串列表
【发布时间】:2015-11-22 22:16:47
【问题描述】:

我是 WPF 新手。我有一个列表框,其中包含各种元素图形元素。 listBox 中的元素链接到一个列表。

目前添加元素我正在使用没有绑定的旧方式:

StackPanel sp = new StackPanel();
string currentDir = AppDomain.CurrentDomain.BaseDirectory.ToString();
TextBox tb = new TextBox()
{
    Text = strContent,
    BorderBrush = new SolidColorBrush(Colors.Gainsboro),
    IsReadOnly = true,
    ToolTip = strNotes,
    FontSize = 12,
    FontWeight = FontWeights.Bold,
    Width = IMAGES_ROW_HEIGHT,
    Height = IMAGES_ROW_HEIGHT / GOLDEN_RATIO,
    Background = null,
    Margin = new Thickness(BUTTON_MARGIN),
    VerticalContentAlignment = VerticalAlignment.Center,
    HorizontalContentAlignment = HorizontalAlignment.Center
};
sp.Children.Add(tb);
Image newResizedImage = ImageUtilities.StrPath2ResizedImageSizeHeight(strPathImage, IMAGES_ROW_HEIGHT);
if (newResizedImage != null)
{
    sp.Children.Add(newResizedImage);
    sp.Orientation = Orientation.Horizontal;
    sp.HorizontalAlignment = HorizontalAlignment.Left;
}
lbxPPgroups.Items.Add(sp);
lbxPPgroups.SelectedIndex = 0;



var newGroup = new PcDmisData.Group();
newGroup.Description = strContent;
var newImage = new PcDmisData.MyImage();
newImage.Image = newResizedImage;
newImage.IsImageEmbedded = false;

newGroup.myImage = newImage;
newGroup.Notes = strNotes;
easyRunData.olstPPgroups.Add(newGroup);

但我知道我做错了,因为我必须手动处理删除、添加、重新排序元素等等。 我希望能够将 listBox 中的元素绑定到以下类的元素:

[Serializable]
public class EasyRunXmlSerializableData
{
    public EasyRunXmlSerializableData()
    { }

    //PcDmis Data           
    public ObservableCollection<PcDmisData.Group> olstPPgroups = new ObservableCollection<PcDmisData.Group>();  
}

public class PcDmisData
{       
    [Serializable]
    public class Group
    {
        public string Description;<---------this for the text of the textbox
        public MyImage myImage;<------------this is the image    
        public string Notes;<---------------this for a tooltip
        public ObservableCollection<PartProgram> partProgramList = new ObservableCollection<PartProgram>();
   }


        [Serializable]
        public class MyImage
        {
            public object Image;
            public bool IsImageEmbedded;
        }

    ....

感谢任何帮助 帕特里克

【问题讨论】:

  • 正如所问,这个问题太宽泛了。简短的版本是您需要了解数据模板,创建一个包含将控制列表项视觉外观的数据的视图模型类,然后在 XAML 中为您的视图模型类型(或类型)声明 DataTemplate绑定到视图模型类中的适当属性,并根据这些属性中的值呈现所需的外观。

标签: c# wpf binding listbox


【解决方案1】:

以下链接应该让您朝着正确的方向开始。

您需要了解当前场景的 DataTemplate 和数据绑定。

MSDN : How to display data in a ListBox

ListBox tutorial basics

ListBox Custom Layout

How to get a ListBoxItem from a data bound ListBox

数据绑定链接

DataBinding - How to

DataBinding - FAQ

Scott's DataBinding tutorial

【讨论】:

    猜你喜欢
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 2011-07-20
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多