WPF中包含画布和Label绑定的ListBox [英] ListBox containing canvas and Label binding in WPF
问题描述
你好,
我有一个在xaml中定义的列表框,如下所示
hello,
I have a listbox defined in xaml as follows
<ListBox Name="lstTemplate" Height="270" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<Canvas/>
<Label/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
现在在代码集后面(我不确定如何在xaml中执行此操作)
lstTemplate.ItemSource = Ada.GetTem();
lstTemplate.DisplayMemberPath ="Contents";
它将在列表框中显示目录.
现在我想要的.
内容"是我要解析的xaml字符串,创建一个元素并添加到列表框中,在我创建的每个元素下方,我想显示标签名称.
另外,如果内容"为空,则添加我自己的默认字符串,该字符串随后将显示默认画布
所以我将代码更改为类似的内容
Now behind the code set(I am not sure how to do this in xaml)
lstTemplate.ItemSource=Ada.GetTem();
lstTemplate.DisplayMemberPath="Contents";
It will display the Contents in the listbox.
Now what I want.
The "contents" is xaml string which I want to parse create an element and add in the list box ,below every element I created, I want to show the label name.
Also if the "contents" is empty I add my own default string which in turn will show a default canvas
So I have changed my code to something like this
var CanvasContent = from s in Adapter.GetTemp() select s.Contents;
foreach (string tempCanvasstring in CanvasContent)
{
if (tempCanvasstring == string.Empty)
{
canvasstring = canvasstring1;
}
else
{
canvasstring = tempCanvasstring;
}
FrameworkElement fe = XamlReader.Parse(canvasstring) as FrameworkElement;
// lstTemplate.Items.Add(fe);
}
var CanvasName = from s in Adapter.GetTemp() select s.Name;
foreach (string tempCanvasstring in CanvasName)
{
// lstTemplate.Items.Add(tempCanvasstring);
}
现在完全不知道如何将fe元素和s.name绑定到我在xaml文件中定义的画布和标签上.
Totally lost now on how to bind the fe element and s.name to the canvas and label that I define in the xaml file.
推荐答案
您可以创建包含所需详细信息的类:
You can create a class that holds the wanted details:
public class MyElement
{
public FrameworkElement Element { get; set; }
public string Name { get; set; }
}
创建所创建类的集合:
private ObservableCollection<MyElement> myCollection;
初始化集合以包含所需元素及其名称,然后将ListBox
的ItemsSource
设置为该集合:
init the collection to contain the wanted elements and their names and, set the ItemsSource
of your ListBox
to that collection:
lstTemplate.ItemsSource = myCollection;
在XAML中,您可以按以下方式绑定数据:
In the XAML, you can bind the data as the following:
<ListBox Name="lstTemplate" Height="270" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Vertical">
<ContentControl Content="{Binding Element}" />
<Label Content="{Binding Name}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel IsItemsHost="True" Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
这篇关于WPF中包含画布和Label绑定的ListBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!