0

i have a list box in which there are different controls like button , text box etc in its item template, i have a collection which i bind with listbox, it works fine , but now i want to move my code to MVVM , and i write some commands in my View Model for clicks events of buttons , how can i bind my collection + my commands to list box ??? because commands are not in the collection, this is the Data Template for my list Box

<DataTemplate x:Key="listItemTemplate">
    <Grid ShowGridLines="False">
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <DockPanel Grid.Row="0" Name="commentsPanel" LastChildFill="False" MinWidth="350">
            <TextBlock  Name="txtUserName" IsEnabled="False" Text="{Binding UserName}" 
                      Width="Auto" DockPanel.Dock="Left" Foreground="GhostWhite" Margin="0,6,0,0"></TextBlock>

            <TextBlock Name="txtDate" IsEnabled="False" Text="{Binding CreateDt}"
                      Width="Auto" DockPanel.Dock="Left" Foreground="Green" Margin="4,6,0,0"></TextBlock>

            <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" Width="{Binding EditPanelWidth}" x:Name="EditDeletePanel" Visibility="{Binding ButtonVisibilityText }">
                <Button Name="btnEdit" Content="Edit" Width="Auto" DockPanel.Dock="Right" Height="20"
                  Click="btnEdit_Click_1" Margin="4,4,0,4" Foreground="GhostWhite" VerticalContentAlignment="Top" Visibility="{Binding ButtonVisibilityText}"></Button>

                <Button Name="btnDelete" Content="Delete" Width="Auto" Height="20" VerticalContentAlignment="Top" DockPanel.Dock="Right" Visibility="{Binding ButtonVisibilityText}"
                Click="btnDelete_Click_1" Margin="4"></Button>

            </StackPanel>

            <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" x:Name="SaveCancelPanel" Visibility="{Binding CancelSaveEnableText}">
                <Button Name="btnSave" Content="Save" Width="Auto" Height="20" DockPanel.Dock="Right" 
                Click="btnSave_Click_1" Margin="4"></Button>

                <Button Name="btnCancel" Content="Cancel" Height="20" Width="Auto" DockPanel.Dock="Right" 
                Click="btnCancel_Click_1" Margin="4"></Button>

            </StackPanel>
        </DockPanel>
        <dxe:TextEdit ShowBorder="False" Grid.Row="1" Name="txtComment" Width="Auto" Foreground="Red"  
                  TextWrapping="WrapWithOverflow" EditValue="{Binding Note}" IsEnabled="{Binding IsCommentTextEnable}">

        </dxe:TextEdit>
        <dxe:TextEdit Text=".............." Grid.Row="2" ShowBorder="False" IsEnabled="False">

        </dxe:TextEdit>
    </Grid>
</DataTemplate>

and here is the collection + my commands which i want to bind to buttons ,

public ICommand CancelCommand
{
    get { return _cancelCommand ?? (_cancelCommand = new CommandHandler(Cancel)); }
    set { _cancelCommand = value; }
}



public TList<ProgramNote> NotesCollection
{
    get { return _notes; }
    set
    {
        _notes = value;
        RaisePropertyChanged("NotesCollection");
    }
}

I know i can use this code to bind my commands with button

<Button Command={Binding CancelCommand}

but this command is not present in the collection , i am new in MVVM , kindly help , may be i am missing some little thing to bind my commands , but i am confused that how to add commands in my collection , so that i can get them in my view

3
  • do you want per item command, that could be triggered on a button rendered for each item in the list box eg. delete, edit etc? or you want to bind a collection of commands to listbox? Commented Jun 10, 2014 at 8:42
  • i want per item command Commented Jun 10, 2014 at 8:49
  • Did you try RelativeSource binding? Example: <Button Command={Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}}, Path=DataContext.CancelCommand} CommandParameter={Binding}/> Commented Jun 10, 2014 at 8:51

3 Answers 3

2

You can bind the commands to your data template buttons etc by finding the appropriate viewmodel

example

 <DataTemplate x:Key="listItemTemplate">
    <Button Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=LixtBox}}" 
            CommandParameter="{Binding}">
 </DataTemplate>

in example we'll find the datacontext of LixtBox which I assume to be your viewmodel then will bind to the command and pass the current object as the command parameter to perform actions on.

you'll then receive the item as parameter in the implementation of your command

public void Execute(object parameter)
{
    ProgramNote note = parameter as ProgramNote;
    //your logic here, eg cancelling download etc.
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx really , now i am able to do it now , actually i was unaware about Relative resource , thanx to all of you really
i will share my answer after 8 hours :)
1

Thanx to all of you specially thanx to @Sheridan and @PushPraj, I am able to do it now , here is the code of data template in which i have a button

<Button Name="btnCancel" Content="Cancel" Height="20" Width="Auto" DockPanel.Dock="Right" 
                        Command="{Binding DataContext.CancelCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=dxe:ListBoxEdit}}"
                               CommandParameter="{Binding}" Margin="4"></Button>

and this is the code of ListBox

<dxe:ListBoxEdit Name="listComments" Grid.Row="1" ItemTemplate="{StaticResource  listItemTemplate}" 
                                                                                 ItemsSource="{Binding NotesCollection}"
                                                                     ScrollViewer.HorizontalScrollBarVisibility="Disabled"  ScrollViewer.VerticalScrollBarVisibility="Visible" >
                                                                </dxe:ListBoxEdit>

and lastly this is my back end code

listComments.DataContext = viewModel;

Comments

0

It's always difficult to answer new user's questions because they always leave out important information from their questions. However, judging by your question text, it sounds to me like you have set your collection property as the DataContext of your Window. If you want to data bind to your commands instead, then you'll need to change the DataContext to the object that contains both the collection and the commands... an instance of your view model:

DataContext = new YouViewModel();

Now that the DataContext is set to an instance of your view model, you can data bind to its properties as you showed us:

<Button Command="{Binding CancelCommand}" />

...

<ListBox ItemsSource="{Binding NotesCollection}" />

Ahhh, sorry I misunderstood - so your Button is inside the ListBox. In that case, you could try something like this:

<Button Command="{Binding DataContext.CancelCommand, 
    RelativeSource={RelativeSource AncestorType={x:Type Window}}}" />

This should reach out of the scope of the collection, looking in the DataContext of a Window, so if you have set the instance of your view model to the Window.DataContext, this should work.

1 Comment

thanx for your reply , i already tried it with window DataContext , but i have a button inside the listbox , is above way of binding will work ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.