下面是代码,摘自一个简单的项目,模拟的是将数据库中的内容放到表格里面,其中有一列,“资源类型”是一个ComboBox,能够让用户进行选择。资源类型绑定在2个对象中,源数据是通过Restypes数组获得,而选中项是通过ResData的FK_RESID来指定:
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public List<ClsResType> GameData { get; set; }
public List<ResData> Restypes { get; set; }
public void LoadResData()
{
Restypes = new List<ResData>();
Restypes.Add(new ResData() { Resid = "1", Resname = "ResName1" });
Restypes.Add(new ResData() { Resid = "2", Resname = "ResName2" });
Restypes.Add(new ResData() { Resid = "3", Resname = "ResName3" });
}
public MainWindow()
{
GameData = new List<ClsResType>();
GameData.Add(new ClsResType() { Name = "GameData-1", FK_RESID = "1" });
GameData.Add(new ClsResType() { Name = "GameData-2", FK_RESID = "2" });
GameData.Add(new ClsResType() { Name = "GameData-3", FK_RESID = "3" });
LoadResData();
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_TypeCombo.ItemsSource = Restypes;
}
}
public class ClsResType
{
public string Name { get; set; }
public string FK_RESID { get; set; }
}
public class ResData
{
public string Resid { get; set; }
public string Resname { get; set; }
}
<DataGrid Name="dgrData"
Height="Auto"
Margin="2,2,12,2"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
AutoGenerateColumns="false"
Background="White"
ItemsSource="{Binding ElementName=ThisWindow,
Path=GameData}">
<DataGrid.Columns>
<DataGridTextColumn Width="80"
MinWidth="20"
Binding="{Binding Name}"
Header="资源Name" />
<DataGridComboBoxColumn x:Name="_TypeCombo"
Width="100"
DisplayMemberPath="Resname"
Header="资源类型"
ItemsSource="{Binding ElementName=ThisWindow,
Path=Restypes}"
SelectedValueBinding="{Binding FK_RESID}"
SelectedValuePath="Resid" />
</DataGrid.Columns>
</DataGrid>
你可以注意到,我在窗口的Load事件中,把_TypeCombo这一列的ItemsSource通过代码绑定到了内部Restypes集合,然后在XAML中,我也设置了其ItemsSource的绑定,你可能会觉得两者重复了,但是!假如把代码去掉,整个程序就不工作了!在Debug的时候会看到会报错:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Restypes; DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=27237168); target property is 'ItemsSource' (type 'IEnumerable')
那么是什么原因导致该绑定失效呢?究其原因,是因为Columns集合只不过是DataGrid的一个属性,不存在于逻辑树和视觉树,所以任何的绑定都是无效的,比如DataContext啊,ElementName啊,Source啊。
具体解决方法可以参考这篇文章: