0

我有一个正在解析的可观察集合 OBSCollection。在这个集合中,我正在检查 name 属性是否为“关键”,如果它是“关键”,那么我正在尝试为每次出现的属性动态创建红色按钮。

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);
        }

现在,上面的代码仅在“关键”属性出现一次时才有效。我如何重写代码以适用于多次出现并因此创建多个按钮?

同样在显示按钮之后,如果用户单击按钮,则应折叠按钮可见属性,并且应从可观察集合中删除该特定项目。我可以从可观察集合中删除按钮,但我无法从 bTapped_Tapped 处理程序将按钮的可见性属性设置为 false。有没有办法解决这个问题?

4

1 回答 1

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>

视图模型和模型:

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 进行操作。它为您提供了您所要求的起点。

希望能帮助到你。

于 2013-06-05T12:21:00.960 回答