簡體   English   中英

StaticResource中的“占位符”綁定

[英]“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 ,但是執行不同的命令。

解決方法-將ListViewTag設置為實際命令,然后從Button綁定到ListViewTag屬性。

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

並在ListView

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM