如何绑定DataTemplate中的特定属性,与ItemsControl中的ItemsControl无关

时间:2012-07-22 22:44:08

标签: wpf datatemplate itemscontrol itemssource

我有以下DataTemplate

        <DataTemplate x:Key="iconButtonsTemplate">
            <StackPanel  Orientation="Horizontal" Margin="120,50,0,0"  HorizontalAlignment="Left" VerticalAlignment="Top"  >
                <icon:IconButton   Command="{Binding Path=DataContext.ButtonClickCommand,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                                   CommandParameter="{Binding Path=CommandParameter}"    TextContent="{Binding TextContent}" ImageSource="{Binding ImageSource}"
                                   IsIconButtonVisible="{Binding Path=MyLocalBoolList}"  />
            </StackPanel>
        </DataTemplate>

我还有ItemsControl,

     <ItemsControl Width="2400"  VerticalAlignment="Top" HorizontalAlignment="Left"
                           ItemsSource="{Binding IconConfigList}"  ItemTemplate="{StaticResource iconButtonsTemplate}" >
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <WrapPanel  Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
      </ItemsControl>

因此可以独立于ItemsControl中的IconConfigList将我的IsIconButtonVisible属性绑定到ViewModel。

2 个答案:

答案 0 :(得分:0)

在绑定中使用ElementName值。

<DataTemplate x:Key="iconButtonsTemplate">
    <StackPanel Orientation="Horizontal" Margin="120,50,0,0"  HorizontalAlignment="Left" VerticalAlignment="Top"  >
        <icon:IconButton Command="{Binding Path=DataContext.ButtonClickCommand,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}"
                     CommandParameter="{Binding Path=CommandParameter}"    TextContent="{Binding TextContent}" ImageSource="{Binding ImageSource}"
                     IsIconButtonVisible="{Binding Path=DataContext.MyLocalBoolList, ElementName=ItemsControlName}"  />
    </StackPanel>
</DataTemplate>

如果ElementName不适合您,请尝试使用RelativeSource。

答案 1 :(得分:0)

IsIconButtonVisible="{Binding Path=DataContext.ViewModelProperty,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 

我希望这会有所帮助。