我有一个可观察的集合OBSCollection我正在解析。在这个集合中,我正在检查名称属性是否“严重”,如果它是“关键”,那么我正在尝试为每个出现的属性动态创建红色按钮。
if (OBSCollection.Any(p => p.Name == "Critical"))
{
criticalcount = OBSCollection.Where(x => x.Name == "Critical").ToList().Count;
for (int i = 0; i < criticalcount; i++)
{
Button temp = new Button();
temp.Background = new SolidColorBrush(Windows.UI.Colors.Red);
temp.Width = 200;
temp.Height = 100;
temp.Content = "Critical";
CriticalPanel.Children.Add(temp);
temp.Tapped += new TappedEventHandler(bTapped_Tapped);
}
private void bTapped_Tapped(object sender, TappedRoutedEventArgs e)
{
var toremovecritical = OBSCOllection.Where(x => x.Name == "critical").First();
uiElements.Remove(toremovecritical);
}
现在上面的代码只有在出现“Critical”属性时才有效。如何重写代码以便多次出现,从而创建多个按钮?
此外,在显示按钮后,如果用户单击按钮,则应折叠按钮visible属性,并且应从可观察集合中删除该特定项。我可以从observable集合中删除按钮,但我无法从bTapped_Tapped处理程序将按钮的visibility属性设置为false。无论如何要解决这个问题吗?
答案 0 :(得分:0)
这是一个使用MVVM的真正基本示例。
XAML:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<GridView ItemsSource="{Binding Things}">
<GridView.ItemTemplate>
<DataTemplate>
<Button Width="100" Height="100" Background="Red" Content="{Binding Name}" Click="CriticalClick" DataContext="{Binding}"></Button>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
ViewModel&amp;型号:
public class ThingViewModel
{
public ObservableCollection<Thing> Things { get; set; }
public ThingViewModel()
{
var allThings = new List<Thing>();
for (int i = 0; i < 30; i++)
{
if (i % 2 == 0)
allThings.Add(new Thing { Name = "Critical" });
else
allThings.Add(new Thing { Name = "`NonCritical" });
}
this.Things = new ObservableCollection<Thing>(allThings.Where(x => x.Name == "Critical"));
}
}
public class Thing
{
public string Name { get; set; }
}
代码背后:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.DataContext = new ThingViewModel();
}
private void CriticalClick(object sender, RoutedEventArgs e)
{
var tappedThing = (Thing) ((Button) sender).DataContext;
((ThingViewModel) this.DataContext).Things.Remove(tappedThing);
}
这是如何使用绑定和MVVM进行的一个非常简单的示例。它为您提供了所要求的起点。
希望它有所帮助。