1

この質問は、この質問のフォローアップです。TreeViewItem現時点での私の全体的な目標はTreeViewItemheader.

ModelViewという、あまりよく知らないツールを使って回答があり、Listのを使えばできるとも言われましたTreeViewItemsListの経験が不足しているため、オプションを検討することにしましたModelView

私の研究では、 のように実際に参照できないため、Listsのは少し異なることがわかりました。これにより、作業がより困難になります。現在の方法を説明し、コードを投稿します。私を正しい方向に導き、コーディングソリューションで回答を提供してください。私は現在、自分の機能に行き詰まっています。その領域で何をしようとしているのかについて、コメントに疑似コードを書きました。TreeViewItemsarraytreeViewListAdd

*注:TreeViewItem別のウィンドウからmy に追加しています

現在、私の追加TreeViewItemプロセスは次のもので構成されています。

  1. 入力された項目が数値かどうかを確認する(DONE)
  2. if数値ではない、break操作(DONE)
  3. else-- 子アイテムの追加を続行します(DONE)
  4. 重複する子をチェック(完了)
  5. if重複が見つかっbreakた操作(DONE)
  6. else-- 続行(完了)
  7. Listの作成TreeViewItem (DONE -- しかし実装されていません)
  8. TreeViewItem新しい子ノードの作成(完了)
  9. TVIheadertextBox (DONE)のユーザー テキストから設定されます。
  10. Listに番号順に追加しようとする関数に渡す(問題領域)
  11. メインウィンドウに並べ替えListを追加(問題領域)TreeViewItem

私の現在のコード:

//OKAY - Add child to TreeViewItem in Main Window
private void button2_Click(object sender, RoutedEventArgs e)
{
    //STEP 1: Checks to see if entered text is a numerical value
    string Str = textBox1.Text.Trim();
    double Num;
    bool isNum = double.TryParse(Str, out Num);

    //STEP 2: If not numerical value, warn user
    if (isNum == false)
        MessageBox.Show("Value must be Numerical");
    else //STEP 3: else, continue
    {
        //close window
        this.Close();

        //Query for Window1
        var mainWindow = Application.Current.Windows
            .Cast<Window1>()
            .FirstOrDefault(window => window is Window1) as Window1;

        //STEP 4: Check for duplicate
        //declare TreeViewItem from mainWindow
        TreeViewItem locations = mainWindow.TreeViewItem;
        //Passes to function -- checks for DUPLICATE locations
        CheckForDuplicate(locations.Items, textBox1.Text);

        //STEP 5: if Duplicate exists -- warn user
        if (isDuplicate == true)
            MessageBox.Show("Sorry, the number you entered is a duplicate of a current Node, please try again.");
        else //STEP 6: else -- create child node
        {
            //STEP 7
            List<TreeViewItem> treeViewList = new List<TreeViewItem>();

            //STEP 8: Creates child TreeViewItem for TVI in main window
            TreeViewItem newLocation = new TreeViewItem();

            //STEP 9: Sets Headers for new child nodes
            newLocation.Header = textBox1.Text;

            //STEP 10: Pass to function -- adds/sorts List in numerical ascending order
            treeViewListAdd(ref treeViewList, newLocation);

            //STEP 11: Add children to TVI in main window
            //This step will of course need to be changed to add the list
            //instead of just the child node
            mainWindow.TreeViewItem.Items.Add(newLocation);
        }
    }
}

//STEP 4: Checks to see whether the header entered is a DUPLICATE
private void CheckForDuplicate(ItemCollection treeViewItems, string input)
{
        for (int index = 0; index < treeViewItems.Count; index++)
        {
            TreeViewItem item = (TreeViewItem)treeViewItems[index];
            string header = item.Header.ToString();

            if (header == input)
            {
                isDuplicate = true;
                break;
            }
            else
                isDuplicate = false;
        }
}

//STEP 10: Adds to the TreeViewItem list in numerical ascending order
private void treeViewListAdd(ref List<TreeViewItem> currentList, TreeViewItem addLocation)
{
        //if there are no TreeViewItems in the list, add the current one
        if (currentList.Count() == 0)
            currentList.Add(addLocation);
        else
        {
            //gets the index of the last item in the List
            int lastItem = currentList.Count() - 1;

            /*
            if (value in header > lastItem)
                currentList.Add(addLocation);
            else
            {
                //iterate through list and add TreeViewItem
                //where appropriate
            }
            **/
        }
}

助けてくれてありがとう。私はこれに取り組んでおり、自分でできることはすべて試していることを示そうとしました.

リクエストに応じて、これが my の構造ですTreeView。第 3 レベル以降はすべて、ユーザーによって動的に追加されます...

ここに画像の説明を入力

4

1 に答える 1

6

Ok。すべてのコードを削除して、最初からやり直してください。

1: WPF で 1 行のコードを記述する前に、MVVM をよく読んでおくことが不可欠です。

あなたはそれについてここここここで読むことができます

<Window x:Class="MiscSamples.SortedTreeView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:cmp="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        Title="SortedTreeView" Height="300" Width="300">
    <DockPanel>
        <TextBox Text="{Binding NewValueString}" DockPanel.Dock="Top"/>
        <Button Click="AddNewItem" DockPanel.Dock="Top" Content="Add"/>
        <TreeView ItemsSource="{Binding ItemsView}" SelectedItemChanged="OnSelectedItemChanged">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding ItemsView}">
                    <TextBlock Text="{Binding Value}"/>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </DockPanel>
</Window>

コードビハインド:

public partial class SortedTreeView : Window
{
    public SortedTreeViewWindowViewModel ViewModel { get { return DataContext as SortedTreeViewWindowViewModel; } set { DataContext = value; } }

    public SortedTreeView()
    {
        InitializeComponent();
        ViewModel = new SortedTreeViewWindowViewModel()
            {
                Items = {new TreeViewModel(1)}
            };
    }

    private void AddNewItem(object sender, RoutedEventArgs e)
    {
        ViewModel.AddNewItem();
    }

    //Added due to limitation of TreeViewItem described in http://stackoverflow.com/questions/1000040/selecteditem-in-a-wpf-treeview
    private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        ViewModel.SelectedItem = e.NewValue as TreeViewModel;
    }
}

2:上記で最初に気付くことは、コード ビハインドが何もしないということです。ViewModel と呼ばれるものに機能を委任するだけです (ModelView ではなく、スペルミスです)。

何故ですか?

それははるかに優れたアプローチだからです。限目。アプリケーション ロジック/ビジネス ロジックとデータを分離して UI から切り離すことは、どの開発者にとっても最高の出来事です。

では、ViewModel とは何ですか?

3: ViewModel は、ビューに表示されるデータをProperties含み、データMethodsを操作するロジックを含む公開します。

したがって、次のように簡単です。

public class SortedTreeViewWindowViewModel: PropertyChangedBase
{
    private string _newValueString;
    public int? NewValue { get; set; }

    public string NewValueString
    {
        get { return _newValueString; }
        set
        {
            _newValueString = value;
            int integervalue;

            //If the text is a valid numeric value, use that to create a new node.
            if (int.TryParse(value, out integervalue))
                NewValue = integervalue;
            else
                NewValue = null;

            OnPropertyChanged("NewValueString");
        }
    }

    public TreeViewModel SelectedItem { get; set; }

    public ObservableCollection<TreeViewModel> Items { get; set; }

    public ICollectionView ItemsView { get; set; }

    public SortedTreeViewWindowViewModel()
    {
        Items = new ObservableCollection<TreeViewModel>();
        ItemsView = new ListCollectionView(Items) {SortDescriptions = { new SortDescription("Value",ListSortDirection.Ascending)}};
    }

    public void AddNewItem()
    {
        ObservableCollection<TreeViewModel> targetcollection;

        //Insert the New Node as a Root node if nothing is selected.
        targetcollection = SelectedItem == null ? Items : SelectedItem.Items;

        if (NewValue != null && !targetcollection.Any(x => x.Value == NewValue))
        {
            targetcollection.Add(new TreeViewModel(NewValue.Value));
            NewValueString = string.Empty;    
        }

    }
}

見る?11 の要件はすべて、メソッド内の 5 行のコードによって満たされますAddNewItem()Header.ToString()ものも、キャストも、アプローチの背後にある恐ろしいコードもありません。

シンプルでシンプルなプロパティとINotifyPropertyChanged.

そして、並べ替えはどうですか?

4:並べ替えは によって実行されCollectionView、ビュー レベルではなくビューモデル レベルで発生します。

なんで?

データは UI での視覚的表現とは別に保持されるためです。

5:最後に、実際のデータ項目は次のとおりです。

public class TreeViewModel: PropertyChangedBase
{
    public int Value { get; set; }

    public ObservableCollection<TreeViewModel> Items { get; set; }

    public CollectionView ItemsView { get; set; }

    public TreeViewModel(int value)
    {
        Items = new ObservableCollection<TreeViewModel>();
        ItemsView = new ListCollectionView(Items)
            {
                SortDescriptions =
                    {
                        new SortDescription("Value",ListSortDirection.Ascending)
                    }
            };
        Value = value;
    }
}

これは、データを保持するクラスです。この場合はint値です。これは、数値のみを気にするためです。これが適切なデータ型でありObservableCollection、子ノードを保持するCollectionViewであり、ソートを処理する です。 .

6: WPF で DataBinding を使用する場合 (これはすべての MVVM に不可欠です) を実装する必要があるINotifyPropertyChangedため、これはPropertyChangedBaseすべての ViewModel が継承するクラスです。

public class PropertyChangedBase:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        Application.Current.Dispatcher.BeginInvoke((Action) (() =>
                                                                 {
                                                                     PropertyChangedEventHandler handler = PropertyChanged;
                                                                     if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
                                                                 }));
    }
}

プロパティに変更があった場合は、次のようにして通知する必要があります。

OnPropertyChanged("PropertyName");

のように

OnPropertyChanged("NewValueString");

そして、これは結果です:

ここに画像の説明を入力

  • すべてのコードをコピーして a に貼り付けるだけでFile -> New Project -> WPF Application、結果を自分で確認できます。

  • 何か明確にする必要がある場合はお知らせください。

于 2013-07-30T16:09:07.763 に答える