WPF 树视图问题
本文关键字:问题 视图 WPF | 更新日期: 2023-09-27 18:34:12
我将如何将以下XML显示到WPF树视图,它必须显示如下
类别名称(简易拼图)
- 拼图名称
类别名称(中型拼图)
- 拼图名称
类别名称(难题)
- 拼图名称
.XML
<?xml version="1.0"?>
<SudokuLibrary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Puzzles>
<SudokuPuzzle>
<Category>Easy Puzzle</Category>
<Name>#1</Name>
<Rank>3</Rank>
<Format>
<string>6,0,0,5,0,4,7,0,0</string>
<string>4,9,5,0,0,8,3,6,0</string>
<string>1,0,7,0,0,0,0,0,0</string>
<string>0,5,0,0,0,1,4,2,8</string>
<string>0,0,0,2,0,9,0,0,0</string>
<string>3,2,1,8,0,0,0,5,0</string>
<string>0,0,0,0,0,0,5,0,3</string>
<string>0,1,3,6,0,0,8,7,4</string>
<string>0,0,8,1,0,3,0,0,2</string>
</Format>
<Solution>
<string>6,3,2,5,1,4,7,8,9</string>
<string>4,9,5,7,2,8,3,6,1</string>
<string>1,8,7,9,3,6,2,4,5</string>
<string>7,5,9,3,6,1,4,2,8</string>
<string>8,6,4,2,5,9,1,3,7</string>
<string>3,2,1,8,4,7,9,5,6</string>
<string>9,7,6,4,8,2,5,1,3</string>
<string>2,1,3,6,9,5,8,7,4</string>
<string>5,4,8,1,7,3,6,9,2</string>
</Solution>
<SaveState>
<string>6,0,0,5,0,4,7,0,0</string>
<string>4,9,5,0,0,8,3,6,0</string>
<string>1,0,7,0,0,0,0,0,0</string>
<string>0,5,0,0,0,1,4,2,8</string>
<string>0,0,0,2,0,9,0,0,0</string>
<string>3,2,1,8,0,0,0,5,0</string>
<string>0,0,0,0,0,0,5,0,3</string>
<string>0,1,3,6,0,0,8,7,4</string>
<string>0,0,8,1,0,3,0,0,2</string>
</SaveState>
</SudokuPuzzle>
<SudokuPuzzle>
**...**
</SudokuPuzzle>
</Puzzles>
</SudokuLibrary>
我在下面尝试了以下方法
<ResourceDictionary>
<XmlDataProvider x:Key="xmldata" Source="Data/SudokuLibrary.xml" XPath="/SudokuLibrary/Puzzles/SudokuPuzzle" />
<HierarchicalDataTemplate x:Key="xmldatatemplate" ItemsSource="{Binding}">
<TextBlock Margin="0" Text="{Binding XPath=Name}" />
</HierarchicalDataTemplate>
</ResourceDictionary>
树视图
<Grid DataContext="{StaticResource xmldata}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TreeView
x:Name="PuzzleTreeView"
Grid.Row="0"
Width="140"
Padding="3"
Margin="10"
ItemsSource="{Binding}"
SelectedItemChanged="PuzzleTreeView_SelectedItemChanged"/>
试试这个。
public class PuzzleName
{
public String Name { get; set; }
public string puzzle{ get; set; }
}
public class Puzzle
{
public String CategoryName { get; set; }
public List<PuzzleName> Children { get; set; }
public Puzzle(string Categoryname)
{
Children = new List<PuzzleName>();
CategoryName= Categoryname;
}
//read the xml file and create an object for the puzzle and load the puzzle name (#1) as its childern
}
在MVVM中...
List<Puzzle> puzzleList = new List<Puzzle>
在视野中...
<TreeView
x:Name="PuzzleTreeView"
Grid.Row="0"
Width="140"
Padding="3"
Margin="10"
ItemsSource="{Binding puzzleList , Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
SelectedItemChanged="PuzzleTreeView_SelectedItemChanged"/>