2011-12-24 32 views
0

请帮助...我在这里做错了什么?试图将列表框绑定到数据表。调试完成后,我在表格中看到数据行,但看到它不与列表框绑定。试图绑定数据表与列表框......错误的东西

仅供参考。 _this是我当前窗口的名称...

  <ListBox Grid.Column="1" ItemsSource="{Binding ElementName=_this, Path=MainCategoriesTable}" HorizontalAlignment="Center" BorderBrush="Transparent" Background="Transparent" x:Name="lbMainCategories"> 
       <ListBox.ItemTemplate> 
        <DataTemplate> 
         <StackPanel Orientation="Horizontal"> 
          <RadioButton Grid.Column="0" Content="{Binding Path=main_category_name}" VerticalAlignment="Center" GroupName="grpMainCategory" x:Name="rdbEnableDisable" /> 
          <Label Grid.Column="1" Width="30" Background="Transparent" /> 
         </StackPanel> 
        </DataTemplate> 
       </ListBox.ItemTemplate> 
      </ListBox> 

下面是财产试图与绑定...

public DataTable MainCategoriesTable 
    { 
     get { return _dtMainCategory; } 
     set { _dtMainCategory = value; } 
    } 
+0

在哪里控制命名为“_this”?你不想绑定到DataContext中的某些东西吗? – 2011-12-24 22:06:20

+0

我也尝试过DataContext。它也没有工作。 _this是我的当前窗口名称等: <窗口x:类= “WpfApplication1.Window3” 的xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” 的xmlns:X = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local =“clr-namespace:WpfApplication1” Title =“Window3”Height =“1000”Width =“1200” x:Name = “_this”> 说实话。几天前我尝试了这个确切的代码,它工作。我不知道我所做的更改或更改了什么,但现在它无法正常工作...... – usergaro 2011-12-24 23:35:21

回答

0

对于XAML来设置数据上下文tocode这背后是什么在起作用我

DataContext="{Binding RelativeSource={RelativeSource Self}}" 

在后面的代码

this.DataContext = this; 

但我用_this就像你用它成功了。

在所有XAML绑定中设置Presentation.Trace = High。这不是确切的语法,但如果您从Presentation开始,它应该很明显。

为什么没有绑定在标签上。

main_category_name是一个公共属性?我注意到它是小写的。

+0

well main_category_name是DataTable中的列名称。 – usergaro 2011-12-25 01:13:39

+0

如果单选按钮可以工作,那么我也会尝试标签。但我被卡在单选按钮上。 – usergaro 2011-12-25 01:14:35

+0

可能是正确的使用DataContext。但我非常有信心,我不需要使用DataContext。所以,只是为了让你的想法一炮而红,我尝试了DataContext,它并没有起作用。:( – usergaro 2011-12-25 01:34:24

0

DataTable像字典一样工作,不像对象。它不会将您的列作为属性公开,但每个DataRow都会显示一个可用于获取单元格值的indexer。因此,你需要使用索引语法:

<RadioButton Grid.Column="0" Content="{Binding Path=[main_category_name]}" VerticalAlignment="Center" GroupName="grpMainCategory" x:Name="rdbEnableDisable" /> 

UPDATE

困扰我的是,你的MainCategoriesTable财产不会通知用户更改另一件事。如果在所有Bindings初始化后都更改,它将不起作用(而DependencyProperty将会因为它总是通知有关更改)。要使其工作,你的上下文类必须实现INotifyPropertyChanged接口和你的财产必须是这样的:

public DataTable MainCategoriesTable 
{ 
    get { return _dtMainCategory; } 
    set 
    { 
     if(value == _dtMainCategory) 
     { 
     return; 
     } 

     _dtMainCategory = value; 
     var h = this.PropertyChanged; 
     if(h != null) 
     { 
     h(this, new PropertyChangedEventArgs("MainCategoriesTable")); 
     } 
    } 
}