我想創建TreeView與複選框,圖像和一些其他信息從UI隱藏。 XAML代碼:WPF TreeView綁定不添加元素
<TreeView Grid.Column="0" ItemsSource="{Binding T1}">
<TreeView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox Name="CheckBoxZ" Content="{Binding name}" IsChecked="{Binding box}" Foreground="{Binding color}" Unchecked="CheckBoxZ_Updated" Checked="CheckBoxZ_Updated"/>
<Image Source="{Binding image}"/>
</StackPanel>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
C#代碼:
namespace App
{
public partial class MainWindow : Window
{
public class TS : TreeViewItem
{
public string color { get; set; }
public string name { get; set; }
public bool box { get; set; }
public string path { get; set; }
public string source { get; set; }
public int operation { get; set; }
public ImageSource image { get; set; }
public ObservableCollection<TS> Items { get; set; }
public TS()
{
this.Items = new ObservableCollection<TS>();
}
}
public TS T1, T2;
public MainWindow()
{
InitializeComponent();
T1 = new TS() { color = "Green", name = "folder", box = true, path = "C:\\folder", source = "D:\\folder", operation = 0, image = X.ToImageSource(System.Drawing.Icon.ExtractAssociatedIcon("D:\\folder\\file.txt")) };
T2 = new TS() { color = "Green", name = "file.txt", box = true, path = "C:\\folder\\file.txt", source = "D:\\folder\\file.txt", operation = 2, image = X.ToImageSource(System.Drawing.Icon.ExtractAssociatedIcon("D:\\folder\\file.txt")) };
T1.Items.Add(T2);
MessageBoxResult result = System.Windows.MessageBox.Show(T1.Items.Count.ToString() + " " + T2.Items.Count.ToString(), "Title", MessageBoxButton.OK, MessageBoxImage.None);
}
public static ImageSource ToImageSource(Icon icon)
{
ImageSource imageSource = Imaging.CreateBitmapSourceFromHIcon(
icon.Handle,
Int32Rect.Empty,
BitmapSizeOptions.FromEmptyOptions());
return imageSource;
}
}
項目被成功添加到變量,但不顯示。應用程序開始沒有錯誤。我沒有這個故障的變種。出了什麼問題?
感謝響應。 1:我在複選框的列表框中使用了相同的算法,它工作。我剛剛嘗試這個,問題沒有解決。我會嘗試。 –
*對不起,列表框使用ObservableCollection。 –