2014-10-01 63 views
0

我有一個ListView從一個靜態資源獲取其Style。舉例來說,我在我的MainWindowViewModel中有一個自定義對象的ObservableCollection。該對象包含一些屬性,包括MyCustomObjectPropertyMainWindowViewModel也有一個ICommand,MyCommandOne「佔位符」綁定在StaticResource中

我的風格(有一些片切出,爲簡單起見):

<Window.Resources> 
    <Style x:Key="MyListViewStyle" TargetType="ListView"> 
     <!--(Removed extra Setters)--> 
     <Setter Property="ItemTemplate"> 
      <Setter.Value> 
       <DataTemplate> 
        <Button Command="{Binding Path=DataContext.MyCommandOne, 
         RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" 
          CommandParameter="{Binding Path=MyCustomObjectProperty}"> 
         <Button.Template> 
          <!--(Styling)--> 
         </Button.Template> 
        </Button> 
       </DataTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 

創建ListView

<ListView Grid.Column="1" 
        Grid.Row="1" 
        ItemsSource="{Binding Path=MyObservableCollection}" 
        Style="{StaticResource MyListViewStyle}" 
        Margin="5" 
        BorderThickness="0" 
        Background="LightGray" 
        /> 

此代碼的工作。當我單擊ListView中的按鈕時,MyCommandOne將使用由單擊列表視圖項目表示的自定義對象的參數執行。

我的問題在這裏:有沒有辦法用某種佔位符代替DataContext.MyCommandOne, RelativeSource...,所以我可以在實際的ListView的標記中指定所需的命令?這樣,我可以用這種風格創建更多ListView,但執行不同的命令。

回答

1

解決方法 - 設置ListViewTag實際命令,然後從Button結合的ListViewTag財產。

<DataTemplate> 
    <Button Command="{Binding Tag, RelativeSource={RelativeSource FindAncestor, 
            AncestorType=ListView}}"/> 
    ........ 
</DataTemplate> 

ListView

<ListView Tag="{Binding MyCommandOne}"/>