2011-03-24 97 views
0

我想把一个枚举器的内容,或一些字符串或特定的DataTable的数组作为DatagridComboBox的项目,所以如何我可以将枚举数或字符串数​​组或DataTable内容绑定到DataGridComboBox?如何将枚举数或变量绑定到WPF中的DataGrid中的DataGridComboBox?

例如,我有一个Datatable我将加载到一个DataGrid,并将记录绑定到自定义列,并取决于单元格的值(从数据表)当列(在DataGrid中)是一个DataGridComboBox它将自动选择DataGridComboBox的相应项目。

作为DataGridTextBox绑定列很容易,但DataGridComboBox列很容易混淆。

我的第一个问题是把项目(一个枚举器,或一个字符串数组,或一个Datatable或其他)到DataGridComboBox,第二个问题是选择相应的项目时,我加载的DataTable其中包含记录到DataGrid。

在此先感谢

回答

2
<Window x:Class="WpfApplication1.Window1" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit"  
    Title="Window1" Height="300" Width="300"> 
    <StackPanel> 

     <toolkit:DataGrid Name="dataGrid" ItemsSource="{Binding Path=.}" AutoGenerateColumns="False"> 
      <toolkit:DataGrid.Columns> 
       <toolkit:DataGridTemplateColumn> 
        <toolkit:DataGridTemplateColumn.CellTemplate> 
         <DataTemplate> 
          <ComboBox ItemsSource="{Binding Path=StringArray}" Width="100" 
             SelectedValue="{Binding Path=SelectedString}" /> 
         </DataTemplate> 
        </toolkit:DataGridTemplateColumn.CellTemplate> 
       </toolkit:DataGridTemplateColumn> 
      </toolkit:DataGrid.Columns> 
     </toolkit:DataGrid> 


    </StackPanel> 
</Window> 

在后面的代码:

namespace WpfApplication1 
{ 
    public partial class Window1 : Window 
    { 
     public Window1() 
     { 
      InitializeComponent(); 
      ObservableCollection<TestClass> collection = new ObservableCollection<TestClass>(); 
      collection.Add(new TestClass()); 
      collection.Add(new TestClass()); 
      collection.Add(new TestClass()); 

      dataGrid.DataContext = collection; 
     } 
    } 

    public class TestClass 
    { 
     private static string[] stringArray = { "Option One", "Option Two", "Option Three" }; 

     public string[] StringArray 
     { 
      get 
      { 
       return stringArray; 
      } 
     } 

     public string SelectedString 
     { 
      get; 
      set; 
     } 
    } 
} 

您需要设置窗口的DataContext /控制背后的一些数据,然后你可以使用这些的属性对象来绑定你的控件。

我希望这有助于

+0

但后来我还有一个问题,我怎样才能从代码隐藏访问变量在XAML?我找到了一些例子,但无论如何,我不明白 – Miguel 2011-03-24 10:42:52

+0

它全都在datacontext中,甚至绑定你需要设置网格的datacontext(或网格的一些父母)到你的数据表的textcolumns到你的数据表。对于所有其他控件/列也是如此 - 您只需将Path设置为datacontext的相应属性即可。 – hyp 2011-03-24 11:19:54

+0

选择组合框中的值我已经理解,但绑定一个组合框的项目,我真的不明白,因为我不知道我如何访问从XAML的DataContext中的任何东西。我看到你的例子,它似乎很容易,但我不能这样做,因为如果我尝试在ItemsSource中设置绑定的路径,他不会识别我的变量。 – Miguel 2011-03-24 18:35:46

相关问题