###前提・実現したいこと
WPFでXMLドキュメントをソースとしてTreeViewを作ろうとしています。
MainWindowViewModelにXmlDocument型プロパティ「PeopleTree」を作ってTreeViewにバインディングしています。
画面内のボタンを押すことでPeopleTreeにノードが追加されるようにしましたが、その変更内容がTreeViewに伝わっていないのか画面の内容が変わりません。
###発生している問題・エラーメッセージ
立ち上げ時にXMLファイルをロードすることで、その内容のツリーを作ることはできています。
しかし、その後ボタンを押してもTreeViewの内容が更新されません。
デバッグして確認したところバインディング元であるPeopleTreeへのノード追加は問題なく行われているようです。
XMLドキュメントへのノード追加はプロパティ変更として扱われないということでしょうか?
初歩的な質問かもしれませんが、解決策を教えていただきたく思います。
よろしくお願いいたします。
###ソースコード
xaml
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication44ViewModel="clr-namespace:WpfApplication44ViewModel;assembly=WpfApplication44ViewModel" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="WpfApplication44.MainWindow" Title="MainWindow" Height="249" Width="276"> <Window.Resources> <HierarchicalDataTemplate x:Key="XmlTemplate" ItemsSource="{Binding }"> <StackPanel> <TextBlock Name="nameTextBlock" Text="{Binding Path=Attributes.ItemOf[Name].Value}" /> </StackPanel> </HierarchicalDataTemplate> </Window.Resources> <Grid> <StackPanel Orientation="Vertical"> <TreeView Name="xmlTree" ItemsSource="{Binding Path=PeopleTree}" ItemTemplate="{StaticResource XmlTemplate}" /> <Button Name="addButton" Command="{Binding AddPersonCommand}" Content="追加"/> </StackPanel> </Grid> </Window>
xaml.cs
using System.Windows; using WpfApplication44ViewModel; namespace WpfApplication44 { /// <summary> /// MainWindow.xaml の相互作用ロジック /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); App app = Application.Current as App; DataContext = app.MainWindowViewModel; } } }
ViewModel
using System.Windows.Input; using Microsoft.Practices.Prism.Mvvm; using Microsoft.Practices.Prism.Commands; using System.Xml; namespace WpfApplication44ViewModel { public class MainWindowViewModel:BindableBase { // TreeViewへバインディングするXmlDocument private XmlDocument peopleTree; public XmlDocument PeopleTree { get { return peopleTree; } set { SetProperty(ref peopleTree, value); } } // コンテキスト public MainWindowViewModel() { PeopleTree = new XmlDocument(); PeopleTree.Load(@"peopleTree.xml"); } // ボタンへバインディングしているコマンド private ICommand addPersonCommand; public ICommand AddPersonCommand { get { return addPersonCommand ?? (addPersonCommand = new DelegateCommand(addPersonMethod)); } } // ツリーの子ノードとして「名無しさん」を追加する private void addPersonMethod() { var ret = peopleTree.CreateElement("person"); ret.SetAttribute("Name", "名無しさん"); peopleTree.DocumentElement.AppendChild(ret); } } }
xmlファイル
<people Name="メンバー"> <person Name="Aさん" /> <person Name="Bさん" /> <person Name="Cさん" /> </people>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/30 12:51
2017/08/31 10:40
2017/09/01 01:32