【发布时间】: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绑定到视图模型类中的适当属性,并根据这些属性中的值呈现所需的外观。