views:

33

answers:

1

I am trying to use the MVVM pattern, and I am wondering where I place an ID value. Do I create a TextBlock that has its visibility property set to collapsed? Or is there a better place to store this kind of data? Currently the command parameter is set to:

CommandParameter="{Binding ElementName=Name,Path=Text}"

But I'd rather it be something like:

CommandParameter="{Binding ElementName=Id,Path=Text}"

I'm totally up for suggestions on what the best way there is to do this, since I'm new to this pattern and presentation language.

<ListBox x:Name="MyListBox" ItemsSource="{Binding MyData, Mode=TwoWay}" BorderThickness="0">        
    <ListBox.ItemTemplate>                
        <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding ElementName=Name,Path=Text}" />
                 <TextBlock Text="{Binding Name}" />
              </StackPanel>  
               </DataTemplate>
    </ListBox.ItemTemplate>            
</ListBox>

EDIT: Option 1

<CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding Id}" />

This option gives me just the Id, which is useful in many situations.

EDIT: Option 2

   <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding}" />

This option gives me the full model, which is even more useful for my particular situation.

+1  A: 

What yout want to do is leave your Id in the data object that is in your items source collection. Just bind the individual item to the stackpanel for each item in the ui list:

<StackPanel Orientation="Horizontal" DataContext="{Binding}"> 
    <CheckBox x:Name="Visible" IsChecked="{Binding Visible, Mode=TwoWay}" Command="{Binding ElementName=MyListBox, Path=DataContext.MyCommand}" CommandParameter="{Binding ElementName=Name,Path=Text}" /> 
    <TextBlock Text="{Binding Name}" /> 
</StackPanel>

Note the DataContext="{Binding}". This syntax binds the whole item object to the property, rather than a property of the object. Now in whatever programmatic code you have for the checkbox, etc, you will have a reference to the checkbox, you can go to the parent stackpanel, access the DataContext property which will have an reference to the item in your collection, from their just retrieve the id.

The great thing about WPF/Silverlight bindings are that you aren't required to expose/bind data into the UI that you dont need visible to the user.

David
Thank you - I didn't realize I could bind the whole object. I'll accept your answer, and post the final solution above.
Blake Blackwell