【问题标题】:changes to the children of the grid dynamically动态更改网格的子级
【发布时间】:2015-04-04 12:23:48
【问题描述】:
我正在尝试使用 Xamarin 表单的网格视图来实现搜索建议功能。我想知道是否有办法根据在搜索框中输入的文本动态更改网格的子级。
grid.Children.Add(new Label
{
Text = x.Text,
TextColor = Color.White,
BackgroundColor = Color.Blue
}, 0, x.Id);
【问题讨论】:
标签:
c#
.net
mvvm
xamarin
xamarin.forms
【解决方案1】:
如果要使用 Grid ,则应指定行和列,否则所有文本将相互重叠。您应该使用 StackLayout 而不是 Grid。
hintSL = new StackLayout(){
HorizontalOptions= LayoutOptions.Fill,
//Orientation = Vertical or Horizontal (however you want)
};
//if you want to add hintsSl into your grid
Grid.SetRow(hintsl, 4);
Grid.SetColumn(hintsl, 4);
searchText.Changed+=(s,e)=>{
hintSL.Children.Clear();
foreach(var hint in YourHintsList)
hintsl.Children.Add(new Label(){Text=hint, and other properties});
};
【解决方案2】:
这里有两种方法可以做到这一点:
首先是使用绑定。将标签的文本字段绑定到根据用户输入而变化的可绑定属性。
第二个是让标签成为持有网格的任何类的成员,而不是匿名的。然后就可以捕捉到用户输入文本时产生的事件(如OnEntryChanged),并在代码中动态设置标签。