【发布时间】:2015-07-25 01:50:04
【问题描述】:
我有一个 WPF 控件窗格,其中包含 16 个相同的子控件,其中包含一个组合框,该组合框需要绑定到后面的父控件代码中的列表。我真的很难让这个列表绑定,直到我发现这个:Binding objects defined in code-behind。
在父控件上设置DataContext="{Binding RelativeSource={RelativeSource Self}}" 允许我直接在子控件上绑定组合框。
问题是现在我想创建一个数据模板来正确显示列表项,但是我在绑定或相对源中没有显示任何内容。
ControlPane.xaml
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="ControlPane"
x:Name="CtrlPaneWpf"
DataContext="{Binding RelativeSource={RelativeSource Self}}"
>
ControlPane.xaml.cs
public class TwoStringClass
{
public string string1;
public string colorHex;
}
public ObservableCollection<TwoStringClass> TwoStringClass1
{
get
{
ObservableCollection<TwoStringClass> cmbclrs = new ObservableCollection<TwoStringClass>();
cmbclrs.Add(new TwoStringClass() { string1 = "This", colorHex = "#FF0000" });
cmbclrs.Add(new TwoStringClass() { string1 = "That", colorHex = "#FF352E2" });
cmbclrs.Add(new TwoStringClass() { string1 = "The Other", colorHex = "#FFF4F612" });
return cmbclrs;
}
}
ChildControl.xaml
<UserControl
x:Name="ChildControl"
>
<ComboBox x:Name="cmbFontColor" ItemsSource="{Binding TwoStringClass1}" >
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding string1}" />
<Rectangle Fill="{Binding colorHex}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</UserControl>
我知道 Binding 正在工作,因为我在 Combobox 中获得了正确数量的(空白)项目,并且如果我删除 ItemTemplate 可以看到类名。
我一生都想不通为什么绑定到属性名称在这里不起作用,就像列表来自控件自己的代码时那样。
我必须向 TextBlock 绑定添加一些其他信息,但无论我尝试什么 DataContext 或 RelativeSource,我总是得到空白项。
【问题讨论】: