这是资源分配文件:TopologyTree.xaml
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:autoDraw.ViewModel.Topology"
>
<HierarchicalDataTemplate x:Key="TopologyTreeBase" DataType="{x:Type local:Base}" ItemsSource="{Binding children}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsChecked}"></CheckBox>
<TextBlock Text="{Binding name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</ResourceDictionary>
Side C#
objectTree.Resources = new ResourceDictionary();
objectTree.Resources.Source = new Uri("GUI/TopologyTree.xaml", UriKind.Relative);
而objectTree是TreeView
但这怎么都行不通。
我已经尝试过如下工作,但是我需要在这里重新定义DataType,所以我觉得它不太好。
var resourceDictionary = new ResourceDictionary();
resourceDictionary.Source = new Uri("GUI/TopologyTree.xaml", UriKind.Relative);
objectTree.Resources.Add(
new DataTemplateKey(typeof(ViewModel.Topology.Base)),
resourceDictionary["TopologyTreeBase"] as HierarchicalDataTemplate
);
更重要的是,我已经尝试将xaml的内容直接放入xmal窗口,如下所示,这样可行,但我需要它进行动态加载,所以它只是证明了我的xmal是好的。
<TreeView Name="objectTree" Grid.Column="4" Margin="3" Grid.Row="1" Grid.RowSpan="3">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Topology.Base}" ItemsSource="{Binding children}">
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsChecked}"></CheckBox>
<TextBlock Text="{Binding name}"></TextBlock>
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
有人可以帮我在C#方面使用它吗?
答案 0 :(得分:3)
嗨,让我告诉你如何做到这一点
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="Red"/>
</Style>
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:uc="clr-namespace:WpfApplication1"
xmlns:local="clr-namespace:WpfApplication1"
Width="1000" Height="1000"
Title="MainWindow" x:Name="abc">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBox x:Name="tbx"/>
</Grid>
tbx.Resources.MergedDictionaries.Add(
new ResourceDictionary { Source = new Uri(@"\Resources\MyResources.xaml", UriKind.Relative) });
不要将ResourceDictionary分配给Source,只需将其添加到MergedDictionary的Collection。
答案 1 :(得分:0)