Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I've got problem to define items in my ItemsControls (or in my view or viewModel). May be I don't know something about mvvm, but here is the question. I have DataTemplate defined as
XML
<DataTemplate>
    <Expander>
        <Expander.Header>
            <StackPanel>
            <TextBlock Margin="2" Text="{Binding Name}" />
            <TextBlock>
                <Hyperlink>
                    <Run Text="Delete group" />
                </Hyperlink>
            </TextBlock>
            </StackPanel>
        </Expander.Header>
        <Expander.Content>
            blah-blah-blah
        </Expander.Content>
     </Expander>
 </DataTemplate>


I have a lot of Expanders, each of them have Hyperlink. And I want Hyperlink will do what it must do - delete group - i.e. remove corresponding Expander. I have read about searching on DataTemplate with Visual and Logical - TreeHelper, but it is bad action - it is not mvvm. I know that I need to wrote some Commmand for Hyperlink, but how can I retrive Expander, which I need to delete, and satisfy mvvm - thats the question.

Any advice, any suggestion...
Posted

1 solution

Hello
You should make a Command, like you mentioned.

You can access the Command in many ways, like this for one example:
XML
<Hyperlink Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Path=DataContext.RemoveExpanderCommand, Mode=OneWay}" CommandParameter="{Binding Path=.}">
  <Run Text="Delete group" />
</Hyperlink>


This example will fint the first Window ancestor. Change it to "UserControl" if you have a UserControl, or to the control name if you have a TemplatedControl.

Note : The are lots of ways to retrieve the command.
You can also use :
Command="{Binding RelativeSource={RelativeSource Mode=TemplatedParent} (...)

to access the "ItemsControl" directly.

You can also use :
Command="{Binding ElementName=MyElementName (...)

to access a specific control by the x:Name property.

I added "CommandParameter" with Path=. to send the current item to the Command, because the "ItemsControl" does not support "SelectedItem".

Then I remove the item from the list.
C#
private void doRemoveExpander(MyClass param)
{
    this.Items.Remove(param);
}


"Items" is a ObservableCollection<Myclass> which holds the items to view in the list. It is given in the "ItemsSource" for the ItemsControl.

Hope that helped a little :-)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900