0

リストボックスを使用して複数の詳細を表示しているWindows Phone 8アプリケーションを開発しています。私の問題は、コードビハインドでデータテンプレートにアクセスしたい、つまり、データテンプレート内で宣言されているすべての子にアクセスできる完全なデータテンプレートにアクセスしたいということです。

リストボックスのデータテンプレート内にある要素の可視性を変更したいだけです。提案をお願いします。

前もって感謝します

4

2 に答える 2

1

i found a solution over this problem

 public static T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
    {
        try
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;

            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return null;
    }

I used this method to find out the first element in my data template and then i changed the visibility of the element. here is an example how to use this method..

ListBoxItem item = this.lstboxMedicationList.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
 CheckBox tagregCheckBox = FindFirstElementInVisualTree<CheckBox>(item);
 tagregCheckBox.Visibility = Visibility.Visible;
lstboxMedicationList.UpdateLayout();

    here i is the index of ListBox item. 
于 2013-08-23T06:18:05.563 に答える
0

DataTemplateバインドされているオブジェクトのプロパティに基づいて、特定の要素を表示または非表示にする が必要なようです。これを取得するためのより良い方法の 1 つは、次のようなことを行うことです。

class MyData
{
   ...
   public string Email {get {...} set {...}}
   ...
}

Visibilityユーザーは電子メール アドレスを持っている場合と持っていない場合があるため、DataTemplate はコンバーターを使用して、Email の文字列値をフィールドの表示または非表示に使用できる値に変換できます。コンバーターは次のようになります。

public class StringNotNullToVisibilityConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string text = value as string;

        if (!string.IsNullOrEmpty(text))
        {
            return Visibility.Visible;
        }

        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML で次のように参照を追加します。

<phone:PhoneApplicationPage.Resources>
    <this:StringNotNullToVisibilityConverter x:Key="StringNotNullToVisibilityConverter"/>
</phone:PhoneApplicationPage.Resources>

最後に、DataTemplate次のような行があります。

<TextBlock Text="{Binding Email}" Visibility="{Binding Email, Converter={StaticResource StringNotNullToVisibilityConverter}}"/>

これは基本的に「メールを表示しますが、メールが null の場合はこのフィールドを非表示にします」と言っています。

于 2013-06-18T23:45:46.830 に答える