2012-04-19 92 views
1

我见在我看来XAML如何将CommandParameter绑定到x:DataTemplate中父控件的名称?

<GroupBox Grid.Row="0" Header="Aktionen bei Prüfung Aufbau"> 
    <ContentControl Content="{Binding BuildUpActions}" ContentTemplate="{StaticResource FullActionListTemplate}" x:Name="BuildUp"/> 
</GroupBox> 

<GroupBox Grid.Row="1" Header="Aktionen bei Prüfung Abbau"> 
    <ContentControl Content="{Binding TearDownActions}" ContentTemplate="{StaticResource FullActionListTemplate}" x:Name="TearDown"/> 
</GroupBox> 

的DataTemplate中以下是在单独的资源

<DataTemplate x:Key="FullActionListTemplate"> 
    <DockPanel LastChildFill="True"> 
     <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right"> 
      <Button Content="Neuer Ausgang" Style="{StaticResource ButtonRowStyle}" 
        Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabControl}}, Path=DataContext.NewFullIOCommand}" 
        CommandParameter="{Binding **?HOW?**}" 
        /> 
      <more buttons here...> 
     </StackPanel> 
     <ContentControl Content="{Binding}" > 

     </ContentControl> 
    </DockPanel> 
</DataTemplate> 

的命令是在视图模型定义的定义

public ICommand NewFullIOCommand 
    { 
     get 
     { 
      if (this._newFullIOCommand == null) 
      { 
       this._newFullIOCommand = new Mvvm.RelayCommand(parm => DoNewFullIO(parm)); 
      } return this._newFullIOCommand; 
     } 
    } 

我想成为能够确定2个列表中的哪一个生成命令。我想要一个CommandParameter传递给包含控件的x:Name的命令处理程序。

如何定义绑定?有没有更好的办法?

+1

您可能想要查看使用'TemplateBinding'或使用'RelativeBinding'和'TemplatedParent'的'RelativeSource'。虽然我不认为你可以获得'x:Name'属性,但是如果你可以返回到你的内容控件,那么也许你可以使用其他属性作为一种“标签”属性。 – CodingGorilla 2012-04-19 13:13:21

回答

3

我看了一下你的示例,并对读取CommandParameter的行进行了快速编辑。在做这个改变之后,我在Snoop(WPF运行时调试器)中检查了这一点,并看到CommandParameter被设置为你所描述的应用所需值。

首先,你可以在这里获得史努比:

Snoop

我能够通过简单的设置CommandParameter到封闭ContentControl中的名称,这样做:

<DataTemplate x:Key="FullActionListTemplate"> 
     <DockPanel LastChildFill="True"> 
      <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" HorizontalAlignment="Right"> 
       <Button Content="Neuer Ausgang" 
       Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type TabControl}}, Path=DataContext.NewFullIOCommand}" 
       CommandParameter="{Binding Path=Name, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContentControl}}}" 
       /> 
      </StackPanel> 
      <ContentControl Content="{Binding}" > 

      </ContentControl> 
     </DockPanel> 
    </DataTemplate> 

作为注意,你的例子几乎在上面一行中包含了一个类似的技术,在这里你绑定到Command属性。

+0

+1非常好!这工作正常。谢谢 – paul 2012-04-23 04:45:39

0

创建一个自我指涉的财产

我讨厌WPF。不过,我只是做了这一点:这个属性添加到您绑定的数据模型类:

public class MyDataObjectItem 
{ 
    //... 
    public MyDataObjectItem Self { get { return this; } } 
    //... 
} 

然后命令参数很简单:

CommandParameter="{Binding Self}" 

或者,显然这个工程

CommandParameter="{Binding}" 

参见https://stackoverflow.com/a/11287478/887092

相关问题