我对 WPF 比较陌生,遇到了一个小问题。使用 HierarchicalDataTemplates,我成功地将 XML 绑定到 TreeView 控件。每个节点都正确渲染(包括 SubstepTemplate 中的标签)。
我什至可以从 SubstepTemplate 中的按钮获取 ViewModel 中的绑定命令,但前提是我为 CommandParameter 输入硬编码值(例如 999)。在我的 XML 中绑定到 commandID 属性的所有尝试都失败了。
这是我现在所拥有的:
XML:
<root xmlns="">
<step label="Step Label 1">
<button label="Button Title 1A" commandID="701" />
<button label="Button Title 1B" commandID="702" />
<button label="Button Title 1C" commandID="703" />
</step>
<step label="Step Label 2">
<button label="Button Title 2A" commandID="801" />
<button label="Button Title 2B" commandID="802" />
</step>
</root>
XAML:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:SidePanel">
<HierarchicalDataTemplate
x:Key="SubstepTemplate"
DataType="button"
ItemsSource="{Binding XPath=*}">
<StackPanel Orientation="Horizontal">
<Button Margin="2" Width="32" Height="32" Command="{Binding ElementName=MyTreeView, Path=DataContext.PluginCommand}" CommandParameter="{Binding XPath=@commandID}" />
<Label VerticalAlignment="Center" Margin="8,0,0,0" Content="{Binding XPath=@label}" />
</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate
x:Key="StepTemplate"
DataType="step"
ItemsSource="{Binding XPath=*}"
ItemTemplate="{StaticResource SubstepTemplate}">
<Expander Header="{Binding Mode=OneWay, XPath=@label}" HorizontalAlignment="Stretch">
</Expander>
</HierarchicalDataTemplate>
<Style TargetType="{x:Type local:SidePanelControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:SidePanelControl}">
<TreeView
Name="MyTreeView"
ItemsSource="{Binding XmlRoot}"
ItemTemplate="{StaticResource StepTemplate}"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
HorizontalAlignment="Stretch">
</TreeView>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
视图模型片段:
public DelegateCommand<string> PluginCommand
{
get
{
if (pluginCommand == null)
{
pluginCommand = new DelegateCommand<string>(ExecPluginCommand, canExecPluginCommand);
}
return pluginCommand;
}
}
public void ExecPluginCommand(string param)
{
LogMessage("In ExecPluginCommand, param = " + param);
}
public bool canExecPluginCommand(string param)
{
return true;
}
需要进入 CommandParameter 以使其正常工作的正确绑定表达式是什么?{Binding XPath=@commandID} 似乎不起作用,我不明白为什么不这样做。