在ListBox.Items发生更改后引发事件

时间:2012-10-30 11:19:41

标签: c# windows-phone-7 listbox

任何人都知道如何在重绘时在ListBox上引发事件。我试图有条件地屏蔽一列中的内容,但条件检查似乎是在绘制列表框之前完成的,因此掩码不起作用,因为没有任何掩盖:

    /// <summary>
    /// Locks or unlocks the quantity textbox based on 100% flour and activates or deactivate weights
    /// </summary>
    private void activatePieceQuantity()
    {
        if (isFlour100Percent())
        {
            ((TextBox)NumberOfItemsTextBox as TextBox).IsEnabled = true;
            weightsActive(true);
        }
        else
        {
            ((TextBox)NumberOfItemsTextBox as TextBox).IsEnabled = false;
            weightsActive(false);
        }
    }

    /// <summary>
    /// Send controls to search with control name and activate or deactivate flag
    /// </summary>
    /// <param name="activate"></param>
    private void weightsActive(bool activate)
    {
        int locationInList = 0;
        foreach (RecipieIngredient ri in activeRecipie.RecipieIngredients)
        {
            SearchTree(this.IngredientsListBox.ItemContainerGenerator.ContainerFromIndex(locationInList), "QuanityWeight", activate);
            locationInList++;
        }
    }

    /// <summary>
    /// Find all weight related objects in the ingredients list and set the visibility accordingly
    /// </summary>
    /// <param name="targetElement"></param>
    /// <param name="flagName">Derived from the Tag of the textbox</param>
    /// <param name="enableFlag"></param>
    private void SearchTree(DependencyObject targetElement, string flagName, bool enableFlag)
    {
        if (targetElement == null)
            return;
        var count = VisualTreeHelper.GetChildrenCount(targetElement);
        if (count == 0)
            return;

        for (int i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(targetElement, i);
            if (child is TextBlock)
            {
                TextBlock targetItem = (TextBlock)child;

                if (targetItem.Name == flagName)
                    if (enableFlag)
                    {
                        ((TextBlock)targetItem as TextBlock).Visibility = Visibility.Visible;
                        return;
                    }
                    else
                    {
                        ((TextBlock)targetItem as TextBlock).Visibility = Visibility.Collapsed;
                    }
            }
            else
            {
                SearchTree(child, flagName, enableFlag);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

我现在知道了,问题是当调用SearchTree函数时没有绘制ListBox,所以从来没有任何DependencyObject传递给它。

我通过在代码中放置一个标志来说明检查已经完成然后从LayoutUpdated事件中调用屏蔽函数来解决问题(在我看来有点hackish)

    private void IngredientsListBox_LayoutUpdated(object sender, EventArgs e)
    {
        if (ingredientsListLoaded)
        {
            activatePieceQuantity();
            ingredientsListLoaded = false;
        }
    }