2013-05-27 44 views
1

我有一個名爲「txtSearch」通過搜索字符串選擇DataGrid中排編程

我也有以編程方式填充一個DataGrid文本框。

現在我想在DataGridView中搜索txtSearch.text,並基於此我想選擇整行。

我希望它以編程方式完成。我的意思是不使用XAML。

可能嗎?

+1

爲什麼你在WPF中實現如果你不想使用XAML?改爲使用Windows窗體。 – Tigran

+0

我已經在winforms中創建了一個應用程序。爲了簡單和良好的動畫,我正在將我的項目轉換爲WPF。 – Vishal

+2

如果你翻譯成WPF,最好花一點時間學習數據綁定,因爲它會給WPF世界帶來巨大的好處。 – Tigran

回答

1

首先,如果你在WPF中做些什麼,你最好做the WPF Way

如果您對學習XAML和MVVM不感興趣,那麼您寧願回到恐龍無用的技術上。

<Window x:Class="MiscSamples.DataGridSearch" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="DataGridSearch" Height="300" Width="300"> 
    <DockPanel> 
     <DockPanel DockPanel.Dock="Top"> 
      <TextBlock Text="Search:" DockPanel.Dock="Left"/> 
      <TextBox Text="{Binding SearchString, UpdateSourceTrigger=PropertyChanged}"/> 
     </DockPanel> 

     <DataGrid ItemsSource="{Binding ItemsView}" AutoGenerateColumns="True"/> 
    </DockPanel> 
</Window> 

代碼背後:

public partial class DataGridSearch : Window 
{ 
    public DataGridSearch() 
    { 
     InitializeComponent(); 

     DataContext = new DataGridSearchViewModel(); 
    } 
} 

視圖模型:

public class DataGridSearchViewModel: PropertyChangedBase 
{ 
    private string _searchString; 
    public string SearchString 
    { 
     get { return _searchString; } 
     set 
     { 
      _searchString = value; 
      OnPropertyChanged("SearchString"); 
      ItemsView.Refresh(); 
     } 
    } 

    private ICollectionView _itemsView; 
    public ICollectionView ItemsView 
    { 
     get { return _itemsView; } 
    } 

    private ObservableCollection<DataGridSearchModel> _items; 
    public ObservableCollection<DataGridSearchModel> Items 
    { 
     get { return _items ?? (_items = new ObservableCollection<DataGridSearchModel>()); } 
    } 

    public DataGridSearchViewModel() 
    { 
     _itemsView = CollectionViewSource.GetDefaultView(Items); 
     _itemsView.Filter = x => Filter(x as DataGridSearchModel); 

     Enumerable.Range(0, 100) 
        .Select(x => CreateRandomItem()) 
        .ToList() 
        .ForEach(Items.Add); 
    } 

    private bool Filter(DataGridSearchModel model) 
    { 
     var searchstring = (SearchString ?? string.Empty).ToLower(); 

     return model != null && 
      ((model.LastName ?? string.Empty).ToLower().Contains(searchstring) || 
       (model.FirstName ?? string.Empty).ToLower().Contains(searchstring) || 
       (model.Address ?? string.Empty).ToLower().Contains(searchstring)); 
    } 

    private DataGridSearchModel CreateRandomItem() 
    { 
     return new DataGridSearchModel 
        { 
         LastName = RandomGenerator.GetNext(1), 
         FirstName = RandomGenerator.GetNext(1), 
         Address = RandomGenerator.GetNext(4) 
        }; 
    } 
} 

數據項:

public class DataGridSearchModel:PropertyChangedBase 
{ 
    public string LastName { get; set; } 

    public string FirstName { get; set; } 

    public string Address { get; set; } 
} 

PropertyChangedBase(MVVM輔助類):

public class PropertyChangedBase:INotifyPropertyChanged 
{ 
    public event PropertyChangedEventHandler PropertyChanged; 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     Application.Current.Dispatcher.BeginInvoke((Action) (() => 
                   { 
                    PropertyChangedEventHandler handler = PropertyChanged; 
                    if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName)); 
                   })); 
    } 
} 

隨機數發生器(只是爲了生成隨機字符串)

public static class RandomGenerator 
{ 
    private static string TestData = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"; 
    private static List<string> words; 
    private static int maxword; 
    private static Random random = new Random(); 

    static RandomGenerator() 
    { 
     words = TestData.Split(' ').ToList(); 
     maxword = words.Count - 1; 
    } 

    public static string GetNext(int wordcount) 
    { 
     return string.Join(" ", Enumerable.Range(0, wordcount) 
              .Select(x => words[random.Next(0, maxword)])); 
    } 

    public static int GetNextInt(int min, int max) 
    { 
     return random.Next(min, max); 
    } 
} 

結果:

enter image description here

  • 完全MVVM。
  • 沒有任何操作任何UI元素的代碼行。這是WPF的方式。
  • UpdateSourceTrigger=PropertyChanged中的TextBox綁定使您在鍵入時進行搜索。
  • 完全強類型的對象模型比使用DataTables和類似的東西好得多。
  • WPF的岩石。只需將我的代碼複製並粘貼到File -> New Project -> WPF Application中即可自行查看結果。
  • 忘記winforms的心態,它是不相關的,笨拙的,生成不好的代碼,只是感覺noob和不成熟。
+0

感謝您的回答。我是一個VB的傢伙。所以我會先轉換你的代碼並嘗試實現它。嘗試後,我會在這裏。 – Vishal

+0

@Vishal有一個[Visual Studio擴展](http://visualstudiogallery.msdn.microsoft.com/94c245e9-547a-4e47-87da-08dbcd283d7f)你可以安裝,執行VB.Net和C#之間的轉換,如果你喜歡。 –

+0

感謝轉換器 – Vishal

0

你可能想使用數據綁定像ff。代碼如下

Dim m_Dt As New DataTable 
Dim m_Bs As New BindingSource 

Private Sub createDatatable() 
    m_Dt.Columns.Clear() 
    m_Dt.Columns.Add("FieldKey", GetType(System.Int16)) 
    m_Dt.Columns.Add("Field1", GetType(System.String)) 
    m_Dt.Columns.Add("Field2", GetType(System.String)) 
End Sub 

Private Sub PopulateDatatable() 
    For i As Integer = 0 To 10 
     Dim dr As DataRow = m_Dt.NewRow 
     dr("FieldKey") = i 
     dr("Field1") = String.Format("field1Value-{0}", i) 
     dr("field2") = String.Format("Field2Value-{0}", i) 
     dr = m_Dt.Rows.Add 
    Next 

End Sub 

Private Sub BindDatatableToDataGridView() 
    m_Bs.DataSource = m_Dt 
    m_DataGridview.DataSource = m_Bs 
End Sub 

Private Sub FindTextAndFocusOnRow() 
    m_Bs.Position = m_Bs.Find("FieldKey", m_TxtSearchText.Text) 
End Sub 


Private Sub ModifyRowValues() 
    m_Dt.Rows(m_Bs.Position)("Field1") = "FieldModified" 
End Sub