2011-03-24 47 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