[英]“Placeholder” Binding In StaticResource
我有一個ListView
從靜態資源獲取其Style
。 例如,我的MainWindowViewModel
有一個自定義對象的ObservableCollection
。 該對象包含一些屬性,包括MyCustomObjectProperty
。 MainWindowViewModel
還具有ICommand
MyCommandOne
。
我的風格(為簡單起見,裁切了一些作品):
<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
,但是執行不同的命令。
解決方法-將ListView
的Tag
設置為實際命令,然后從Button
綁定到ListView
的Tag
屬性。
<DataTemplate>
<Button Command="{Binding Tag, RelativeSource={RelativeSource FindAncestor,
AncestorType=ListView}}"/>
........
</DataTemplate>
並在ListView
:
<ListView Tag="{Binding MyCommandOne}"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.