Pregunta

How can i bind a command parameter to self?

I try like this:

<ListBox.ItemContainerStyle>
   <Style TargetType="ListBoxItem">
      <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
               <Button Content="G"
                       Background="Green"
                       Foreground="White"
                       Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
                                 Path=DataContext.LabelGoodCommand}"       
                       CommandParameter="{Binding /}"
                       Width="20" Height="20" />
            </ControlTemplate>
         </Setter.Value>
      </Setter>
   </Style>
</ListBox.ItemContainerStyle>

But this doesn't work. In viewmodel listbox items binding to ObservableCollection.

¿Fue útil?

Solución 2

If by "self", you mean the button, you can do that:

CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"

If you want the current DataContext, just don't specify the path:

CommandParameter="{Binding}"

Otros consejos

CommandParameter="{Binding RelativeSource={x:Static RelativeSource.Self}}"

By this you can get the Control and in your Execute method, Use as like this,

if(pram is Button)
{
    var model = ((Button)pram).DataContext;
}

you can get the Model here.

OR

           <Button Content="G"
                   Background="Green"
                   Foreground="White"
                   Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
                             Path=DataContext.LabelGoodCommand}"       
                   CommandParameter="{TemplateBinding DataContext}"
                   Width="20" Height="20" />

OR

<Button Content="G"
                   Background="Green"
                   Foreground="White"
                   Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},
                             Path=DataContext.LabelGoodCommand}"       
                   CommandParameter="{Binding DataContext,RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}"
                   Width="20" Height="20" />
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top