我想遍历Row
的{{1}}中的特定Grid
,并在此Row的每个单元格内获取Wpf
。我已经搜索了很多,但是还没有找到任何解决方案! UI元素的类型为UI Element
。
说明
如您在所附图像中看到的。我有一个TextBlock
,其中有一些Grid
和Rows
。我想遍历Columns
,并将Row 0
的每个TextBlock.Text
中的cell
与一些Row 0
进行比较。怎么做 ?
答案 0 :(得分:0)
首先,您可以获取Grid的Children集合,然后可以检查每个元素位于其哪一行:
foreach (var element in grid1.Children) {
if (grid1.GetRow(element) == 0) {
//now you get all the UIElements in the first row
}
}
答案 1 :(得分:0)
要保留分开的View和ViewModel而不是使用CodeBehind进行逻辑处理,我建议使用DataGrid和Binding进行搜索,因此View类似于:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}" Grid.Row="0" Grid.Column="0"></TextBox>
<TextBlock Text="{Binding SearchResult}" Grid.Row="0" Grid.Column="1"></TextBlock>
<DataGrid ItemsSource="{Binding Entries}" Grid.Row="1" Grid.ColumnSpan="2">
</DataGrid>
</Grid>
因此,SearchText是要搜索的内容,而SearchResult是结果。两者都绑定到ViewModel。并且Connected View Model包含DoSearchBay(),用于使用当前SearchText的值更新SearchResult字段,代码如下:
public class ViewModel: INotifyPropertyChanged
{
private String _searchText = "Bay?";
private String _searchResult = "N/A";
public ObservableCollection<MyDataObject> Entries { get; set; }
public string SearchText
{
get => _searchText;
set
{
if (value == _searchText) return;
_searchText = value;
DoSearchBay();
OnPropertyChanged();
}
}
private void DoSearchBay()
{
var sel = Entries.Select((dm, index) => new { index, dm.Bay}).FirstOrDefault(obj => obj.Bay.Equals(_searchText, StringComparison.OrdinalIgnoreCase)) ;
if (sel != null)
{
SearchResult = "Found in row " + sel.index;
}
else
{
SearchResult = "N/A";
}
}
public string SearchResult
{
get => _searchResult;
set
{
if (value == _searchResult) return;
_searchResult = value;
OnPropertyChanged();
}
}
public ViewModel()
{
//Create Fake values
Entries = new ObservableCollection<MyDataObject>();
Entries.Add(new MyDataObject() {Bay = "Bay1", Am9 = "value1-1", Am10 = "value1-2", Am11 = "value1-3" });
Entries.Add(new MyDataObject() { Bay = "Bay2", Am9 = "value2-1", Am10 = "value2-2", Am11 = "value2-3" });
Entries.Add(new MyDataObject() { Bay = "Bay3", Am9 = "value3-1", Am10 = "value1-2", Am11 = "value3-3" });
}
// ToDo Implement INotifyPropertyChanged...
}
包含数据的模型如下所示:
public class MyDataObject
{
public String Bay { get; set; }
public String Am9 { get; set; }
public String Am10 { get; set; }
public String Am11 { get; set; }
}