A-D-D-F_Toxic A-D-D-F_Toxic - 17 days ago 5
C# Question

"Placeholder" Binding In StaticResource

I have a

ListView
that gets its
Style
from a static resource. For an example, I have an
ObservableCollection
of a custom object in my
MainWindowViewModel
. This object contains a few properties, including
MyCustomObjectProperty
. The
MainWindowViewModel
also has an
ICommand
,
MyCommandOne
.

My style (with some pieces cut out, for simplicity):

<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>


Creating the
ListView
:

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


This code works. When I click a button in the
ListView
,
MyCommandOne
is executed with the parameter from the custom object that is represented by the clicked list view item.

My question here: is there a way to replace
DataContext.MyCommandOne, RelativeSource...
with some sort of placeholder, so I can specify the desired command in the markup of the actual
ListView
? This way, I can create more
ListView
s with this style, but executing different commands.

Answer

Workaround - Set Tag of ListView to actual command and then bind to Tag property of ListView from Button.

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

and in ListView

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